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
@Getter
and@AllArgsConstructor
can 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.