This post originated from an RSS feed registered with Java Buzz
by dion.
Original Post: How closures and the like make me think differently
Feed Title: techno.blog(Dion)
Feed URL: http://feeds.feedburner.com/dion
Feed Description: blogging about life the universe and everything tech
Each language and environment that you program in tends to have a feel. When you are deep into one community, you take on its "slang".
This can be good, as you can learn a lot, and it can be a good way to communicate. However, it is good to visit other countries and learn other cultures.
Here is one small example of how I may write different code in Java, now that I also live in other communities such as Groovy, LISP, etc.
I was looking at a project, which had a lot of conversion code, to pretty-print contents of arrays, collections, and the like.
The way the team handled it was to have a bunch of methods on the model objects which would iterate through their collections/arrays and would built a nice String.
I would think of this problem differently:
What is consistent? The formatting of the elements is always the same
What varies? The actual data that you want to display
Now, you could of course, grab a Jakarta Commons library to spew the info out for you, but if you want to control it yourself I would do the following:
Put the common code in one place
PrettyPrinter.java has methods such as:
String convertCollectionToString(Collection theCollection, StringConversionFormatter formatter);
String convertArrayToString(Collection theCollection, StringConversionFormatter formatter);
Put the varied code in via a closure
The StringConversionFormatter interface encapsulates the variety. So, to do a conversion of a Role domain object I would have something like:
String result = PrettyPrinter.convertCollectionToString(roles, new StringConversionFormatter() {
public String format(Object o) {
return ((Role)o).getName();
}
});
Man I wish we could have PrettyPrinter.convertCollectionToString(roles, { return o.name })
;)