Making a readeable code, more and more readeable
One thing groovy and grails really rocks, is the legibility of the generated code. It’s amazing how this Java code below
Contact boringObject = new Contact();
boringObject.setNome("Lucas");
boringObject.setIdade(24);
boringObject.setEmail("lucastex@gmail.com");
boringObject.setPhone("55 11 9999.9999");
boringObject.setDateCreated(new java.util.Date());
can turn into this beautiful code:
def c = new Contact() c.name = "Lucas" c.age = 24 c.email = "lucastex@gmail.com" c.phone = "55 11 9999.9999" c.dateCreated = new Date()
Yeah, I know, this is simple and it’s already done in most frameworks via OGNL and reflection, but groovy bring this feature natively and makes the code human-readeable removing all unnecessary commas, parenthesis and other symbols. Groovy brings the code to the closest natural reading language I ever saw! You can see this by studying the GORM dynamic finders, that is a real good example of what I’m saying; you think, you transcript and that’s the code.
Another useful feature, to make the code more readeable, is the with builder block. Imagine the snippet above, all properties that we’re setting, we’re setting in the same object, so why do we have to mention the object everytime? So, you can use this block to set everything in the same object. Try the code above:
def cb = new Contact()
cb.with {
name = "Katie"
age = 24
email = "katie@xpto.com"
phone = "55 11 8888.8888"
dateCreated = new Date()
}
That’s why I like groovy so much, you won’t waste your time on “syntax learning”. All you need to do is read the code!
Comments(4)
You forgot:
def c = new Contact( name: “Lucas”,
age: 24
email: “lucastex@gmail.com”
phone: “55 11 9999.9999″
dateCreated: new Date() )
@Tim
Hello Tim!!! Thanks for visiting! That’s true… The named parameters is either great!
Thanks for commenting about!
You can do it in Java too.
Contact c = new Contact() {{
name = “Lucas”;
age = 24;
phone = “9999999999″;
email = “lucastex@gmail.com”;
dateCreated = new Date();
}};
Or enve in Scala:
val c = new Contact() {
name = “Paulo”
age = 26
email = “paulosuzart@gmail.com”
phone = “99999999999″
dateCreated = new Date()
}
Groovy is nice like others.
Going further, given a Erlang record:
-record(contact, {name,age,phone,email,dateCreation}).
C = #contact{
name=”Lucas”,
age=24,
phone=”9999999999″,
email=”lucastext@gmail.com”,
dateCreation=date()}.
Its simple too, isn´t it?