Create a gist now

Instantly share code, notes, and snippets.

A strong frame for functional programming in Java

A strong frame for functional programming in Java

Regarding functional programming in Java, the most important design rule is to avoid mutability. We use it only in places, where it makes sense and we use it internally, only, i.e. mutability does not leak to the outside as public API. Within the last years I deduced these three simple rules to achieve it:


i. Don't try to create purely functional programs with Java. Simply spoken, Java is not the right language for that.

ii. It is most important to follow these rules consistently and make no exceptions other than stated.


  1. Never ever mutate a method argument, no matter if it is primitive or an object reference. For reasons of readability, we do not make method args final.
  2. Think in immutable values and expressions
  • Make instance variables final and provide only one singleton constructor to initialize them. Our code does not contain setters. Exception: builders. Note: If more constructors are needed, provide static factory methods.
  • Don't break the control flow, always use if-else in favor of if. Exception: guards.
  1. Make local variables final. This automagically leads to functional programs. Because of 2. we need to implement functions (read: methods) to compute values.

Extra points: Make (private) functions static, if they do not depend on the state of an encapsulating class instance.

Javaslang itself is built from the ground up by consistently following these rules. It does embrace this style of programming and provides you with powerful functionality to do so also. The upcoming 2.0.0 release comes along with full fledged immutable collections you know from Clojure and Scala. Stay tuned!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment