Skip to content

Instantly share code, notes, and snippets.

@danieldietrich
Last active December 6, 2015 17:43
Show Gist options
  • Save danieldietrich/4f4489f1cacd31709900 to your computer and use it in GitHub Desktop.
Save danieldietrich/4f4489f1cacd31709900 to your computer and use it in GitHub Desktop.
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:

Preamble

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.

Rules

  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