Don’t make me think

Hamcrest matchers provided a good way of expressing the assertion in the tests. Combined with the method name and the way you write your assertion it becomes expressive. Bringing it into the middle of development phase when all the other tests have been written using regular assertions was not so desired. So restricted that to starting something from scratch.

Java programmers would have gone through the boring ‘for loop’ and collections manipulations for any applications. Both in the tests and production code it was almost necessary to transform view objects (a necessary evil) to and from models or go through a list and collect the just the names etc. CollectionUtils from apache provided a good way to work through the mundane for loops and do most of that stuff. CollectionUtils.collect(list, new Transformer() {<transformer code>}),  CollectionUtils.select(list, new Predicate() {<predicate code>}) did good help to reduce remove the for loops out of sight.

I then moved on to Groovy which is when I got smitten by the ease at which we can use collections. All we need to do was to call .each or .collect on the collection and put the respective code in the closure. Having tasted this going through the CollectionUtils in java was suddenly looking like an eye sore on the code. I discussed with another developer (incidentally his name is the same as mine) about the problem. He immediately jumped in and said that he had used LambdaJ and it uses Hamcrest matchers. We immediately explored through the code and started replacing Collections.sort to LambdaJ alternative. The code

Collections.sort(personList,new Comparator() {

//comparator code

})

changed to Lambda.sort(personList, on(Person.class).getAge())

Once we tasted success with the first replacement, we went scouting through the code for “for loops & CollectionUtils” and ended up having interesting looking self explanatory code like

Lambda.filter(having(on(Student.class).getAge()) ,is(greaterThan(20)),studentsList)

On doing the static import, the Lambda prefix also disappears. The power of Hamcrest matchers and LambdaJ’s thoughtfully made collection utilities help in making Java code more easy to read. It also has brought closure support to Java (Limited somewhat due to Java’s nature) which looks promising but I am yet to explore its full potential.

As more and more people are getting their hands on other programming languages and switching back to Java due to client requirements are making Java more and more readable and easy to use with these kind of APIs. You can spend more time thinking about the functionality, design rather than getting bored with boilerplate stuff. What else is in store from polyglot programmers?


Leave a comment