Functional Programming in Java

Practical tips for writing FP in Java

·

1 min read

Recently, I have been trying to write more functional code in Java. Now, Java does not have built-in support for some functional concepts (like immutability), but there are a lot of things we can do to make code more functional (hence better).

I have created these rules that can help me to achieve this:

  1. There should be no classes! But, because in practice everything in Java should be within a class, we end up creating classes (as a means of grouping functions), with only static methods.
  2. All logic functions (calculations, logging, I/O, ...) should be static.
  3. Define fields "final" as much as you can.
  4. For data objects, define a simple POJO, private ctor and a public static creator function (like of).
  5. In data objects, all fields must be "private final", with only getter functions.
  6. Lombok's @Getter and @AllArgsConstructor can be useful to reduce boilerplate code, but I really prefer Java records which have been recently introduced.
  7. Don't forget, even rules are meant to be broken. So use your own judgement.