Techconative Logo

Java Micro Hygiene :

  Under the lens of Functional Programming

Wed Mar 29 2023

Java Micro Hygiene - Under the lens of Functional Programmingimage

Context

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.

The list

Getting straight into the list..

Avoid mutating data

Avoid patterns in which you create data and then changing it.

For example,

Instead of doing something like this,

User aUser = new User(); aUser.setName("some-name"); aUser.setFirstName("some-name");

Prefer this,

User aUser = new User("some-name", "FName");

Provided the requirement constructor, or static method to create the instance has been added.

With Collections, instead of,

List<Roles> roles = new ArrayList<>(); roles.add(role1); roles.add(role2);

Use,

List<Roles> roles = Arrays.asList(role1, role2); // OR List<Roles> roles = List.of(role1, role2);

The same logic can be applied for other collections as well, leveraging the static methods(of) that are available on other collections.

Avoid iterating, use streams instead

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 for/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.

Go for record whenever possible

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.

Leverage Closures

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,

String someVariable = null; if(aList != null) { someVariable = aList.get(0); }

Can be turned into,

var someVariable = nullSafe(aList, (l)-> l.get(0));

This related reading could also helpful on knowing more about the thought process.

We would love to hear from you! Reach us @

info@techconative.com

Techconative Logo

More than software development, our product engineering services goes beyond backlog and emphasizes best outcomes and experiences.