Functional Programming in Java
Practical tips for writing FP in Java
Hands-on technology leader with 10+ years building scalable, mission-critical systems at Goldman Sachs, Brevan Howard and fast-growing fintechs. Expert in cloud-native architectures, distributed data pipelines and high-throughput systems; experienced in migrating legacy platforms and designing AI-enabled services. Proven track record delivering reliable platforms that process millions of transactions daily.
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
of). - In data objects, all fields must be "private final", with only getter functions.
- Lombok's
@Getterand@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.