Thomas Skardal

Hello, computer.

Show me what, not how!

February 12, 2015

Java 8 was released last year, and with it came lambdas and better possibilities for functional programming. This is old news to a lot of people, but if you have been living exclusively in Java lately you might wonder why you should bother with a new style of coding when the old way is just as “readable” in most cases? I see this as a big improvement and benefit, but some people do not.

The old way

List<String> startingWithT = new ArrayList<>();
for(String s : allNames) {
  if (s.startsWith("T")) {
    startingWithT.add(s);
  }
}

The new way

List<String> startingWithT = allNames.stream()
        .filter(n -> n.startsWith("T"))
        .collect(Collectors.toList());

The first sample is familiar and all, but there’s also more room for stupid errors. The last example is more readable (as in declarative, not familiar!). When you’re used to this way of coding, you’ll have fewer parts of the code that needs focus. No reason to enter “human compiler mode” to ensure that you’re iterating correctly and adding to the right list.

This is of course just one of many examples, but I hope it still proves a point.

To be honest, I prefer using the functional way even in earlier versions of Java. By using the functional parts of Guava I can write code that feels and reads like this even in Java 7 (which I’m using at work). Sure, it’s quite verbose and all, but I tend to see through the boilerplate code and focus on the small important parts of the filters and transforms. In the imperative code all of these lines matters. In functional approach most of them don’t, and messing it up would probably causing a compiler error instead of a hard to find bug!