Functional Java is Immutable Java

You could fill a book on programming styles. And some people do.

The guidelines for coding in Java, my language of choice, are fairly fluid but there is usually a general consensus of opinion on most topics. One topic of recent years is: Always declare variables as final.

Why is this more functional?  Functional programming avoids mutable state. It is also easier to reason about immutable objects, e.g.Imagine looking for a bug with the following:

I have a 3 ‘variables’ and a NullPointerException. 2 of the values are constants. I already have a good idea what has happened.

The idea is that if a variable can have its value changed it can be confusing and lead to bugs. If every variable is final you have only to know what value it was initialized with. There is a peculiarity when this style is adopted (and eclipse will do this for you if you configure it) – anything non-final appears like a warning, particularly useful for parameters which should remain constant through a method invocation. Imagine a function working on width and height that changes the height halfway through.

Making all variables final used to be tough as some people believed in having only one return point in a method. This argument has been answered in the Java world by Kent Beck, one of the founders of XP / Agile and creator of the JUnit framework. Single Entry Single Exit, he says,

was to prevent the confusion possible when jumping into and out of many locations in the same routine. It made good sense when applied to FORTRAN or assembly language programs written with lots of global data where even understanding which statements were executed was hard work … with small methods and mostly local data, it is needlessly conservative.

As well as recommending making values final where possible I’d recommend having your IDE warn you about it too.

This post was originally made on my other blog at https://vfleetwood.wordpress.com/ – I thought it would be useful here with the advent of functional Java 8. Thanks for reading.