Donnerstag, 7. Juli 2011

Dynamic data definitions the Groovy way

Hello everyone did you have ever had the need to define some data which quickly can be processed? Well there are myriads of ways. There is xml, and you can roll your own parser, you can use property files. But there is another way. You could do it in a dynamic scripting language.

Well we have Groovy and we could use the Groovy builders as shown here. The Problem with the builders is that you might lose some realtime syntax checking, some tools already have. I want to talk about a different way to describe data. A combination of properties and closures to keep the syntax lean. Lets have a look at an example.



Normally we would have to generate the class and set the properties or we would have to define constructors with property lists. There is another way, we can use closures to set the properties dynamically at object creation



What we do here is to generate a new object and dynamically set helloWorld which has a predefined value of "helloworld" to add. Another way to do the same would be following:



Or like following:



Same result different angle to the approach. What we do here is following we use the internal map semantics groovy uses to store properties to set the value of helloWorld to a new value. In the first example we do it explicitely in the second one via dynamic parameter maps for the constructor. Both cases would result in the same result! Lets have a look on how compact this approach is:



Now think how much more code you would have in xml or how much more effort this would be by rolling your own data definition language. The good thing is you can set your properties to predefined defaults and then use the closures to override the values you want to change. The best thing however is you can use all this seamlessly from java. A Java Class simply would have to call the setters and getters of the properties of the generated objects to access those values! The groovy compiler takes care of the rest!

Keine Kommentare:

Kommentar veröffentlichen