Functional Programming in Java
Practical tips for writing FP in Java
·Dec 5, 2021·
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:
- 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.
- All logic functions (calculations, logging, I/O, ...) should be static.
- Define fields "final" as much as you can.
- For data objects, define a simple POJO, private ctor and a public static creator function (like
- In data objects, all fields must be "private final", with only getter functions.
@AllArgsConstructorcan be useful to reduce boilerplate code, but I really prefer Java records which have been recently introduced.
- Don't forget, even rules are meant to be broken. So use your own judgement.