Sonntag, 15. Juni 2008

It's already a long time since my last post. Got caught in my current project.However, recently I used some time to have a look at some topics of interest.One of these points were Groovy. Currently, there is a lot of momentum in the area of dynamic languages. Groovy is part of it and it's really cool. I think it as a natural complementary fit to Java if used in the right way.You can choose between dynamic and static typed programming. This freedom may be heaven and hell. However, it brings some useful and well though language constucts and features to ease programming. Just to mention a few: Closures, Everything is an object, Handling of list and maps, Proxying, Meta-class programming, construction of DSL.

The latter one is based on a groovy's builder concept.Since I wanted to check it out, I used my favourite object oriented database db4o and built a db4o builder on top of it. It is hosted on google. You can download it here or browse the svn for the latest code.

The Groovy builder pattern is a powerful concept to provide arbitrary nested trees of objects or events, providing a tree-like façade. Though the db4o API is already very simple to use on its own, the db4o builder provides another easy way of accessing db4o databases. A Groovy builder relies on closures to setup its tree-like structure based on nodes.

Db4o has a very easy Java API that can be used in groovy as is. Open a database by and work on a Db4oContainer object to store and access objects by simply calling set and get or performing complex queries.

However, in groovy you can leverage the builder concept to let it open and close the database automatically. Same when specifying a query the builder may execute the query automatically when the query has been set.

As you see, there is nothing special in creating a db4o builder object. You create it like any other java or groovy object. A db4o database is opened and close by using the file method (well to open a remote database server there is also a client method that takes the host, port, user name and password which should work but I haven't tested it yet).

The db4o database is opened on entering the file node and closed on leaving it. The file method is equipped with a closure to take the custom action.

Within the closure, we now can use additional methods to store, update, delete or query objects. In order to store objects, you simply call the set method within the closure of the file method. The set method takes the object to store as argument.

If you need access to the opened db4o database, the db4o builder provides access to a variable called objectContainer which is of type com.db4o.ObjectContainer and represents the opened db4o database connection.

SQL Queries are done the same way by using a special node called sqlquery. In addition to query the results after the node and outside of the builder, the query result can be processed within the sqlquery node itself as well. An example: