Wednesday, November 14, 2007

Taking ideas from Ruby - 1

Ruby has gained popularity recently in dynamic language space. It does have some features which somehow appears elegant. Probably java can add some syntactic sugar, inspired by Ruby.
One small thing (but usually repeated one) is to test whether a Map contains an entry before adding items to it.
For eg:

Map myMap = getMap();
if (!myMap.contains("Count")) {
myMap.put("Count", 2);

Ruby has a ||= operator which does this checking implicitly.
With that the code will look like:

Map myMap = getMap();
myMap["Count"] ||= 2;