As we’re working with Junior to Mid-level engineers recently, we came across certain repeated situations in Java, which we felt could make the code better readable.
This is more from the perspective of wisdom gained by programming functional languages like as Clojure and the direction of evolution of Java.
This blog more of WIP and we tend to add more points as we figure out.
Getting straight into the list..
Avoid patterns in which you create data and then changing it.
Instead of doing something like this,
Provided the requirement constructor, or static method to create the instance has been added.
With Collections, instead of,
The same logic can be applied for other collections as well, leveraging the static methods(
of) that are available on other collections.
Though people are aware of streams, many people still use iterations. Iterations make code less concise. There might be certain situations in which you feel iterations to be more performant.
The example could be exhaustive, so I’m not giving anything specific here. Ideal goal is, try not to use iterations at all and replace all your
while with streams and see how clear and concise your code is.
Not all the times the iterations are avoidable. And sometimes the better replacement for iteration is recursion. But when using Java, beware of the fact that Java doesn’t support TCO and you might end-up blowing the stack.
This is a means to address #1(avoiding mutation) on certain cases. With JDK 14, we have records for simple Pojos and go with classes only if you think you need it.
Closures available in Java as Functional interfaces. Having utilities leveraging closures could help you to write more abstract and reusable. For example, this utility always comes in all of our projects to write concise code.
For example, with the above utility, the code like this,
Can be turned into,
This related reading could also helpful on knowing more about the thought process.