A Minor But Useful Refactoring Technique That Would Reduce Your Code Footprint (Part 1)

Finally, we upgraded to Java 11 from Java 8.

That was a long-awaited move, but I’m pleased that we eventually made it.

The next thing that came to mind when I stated this was, “Why not Java 17 directly?”

Eventually, we would move to 17, but we had to begin someplace.

And the transition to 11 was not easy either.

We had several dependencies with Mockito, which made the journey somewhat tricky, but we were able to manage it.

Anyway, since we have already moved to 11, I was wondering what smaller changes I could make to the codebase immediately.

I was looking for smaller changes, not major ones. So this article is about the first step of some smaller changes that I made. 

Immutable collections

For many reasons, we often need immutable collections.

However, Java collections are inherently mutable. There was no simpler way to make them immutable.

The option in our code repository appeared as follows:

private static final List<RuleType> OUR_FAVORITE_RULES;

static {
final List<RuleType> favoriteRules = new ArrayList<>();
OUR_FAVORITE_RULES = Collections.unmodifiableList(favoriteRules);


Interestingly, Java 9 introduced the Factory method List.of() that can be used to remove the entire block.

  private static final List<RuleType> OUR_FAVORITE_RULES = List.of(RuleType.RULE_ONE,
RuleType.RULE_TWO, RuleType.RULE_ETC);

There are similar methods available for set and map. Example:


Map.of(“bazlur”, “Bangladesh”,
“Geertjan”, “Netherlands”);

Null checking if blocks

In the huge projects that have accumulated code over many years, you will find many if blocks that only check whether the object is null or not. Based on that, it takes specific actions. 


if (fileName == null) {
builder.append(“Unknown Source”);
} else {

There are multiple ways to turn it into oneliners. 

builder.append(fileName == null ? “Unknown Source” : fileName);


builder.append(Objects.requireNonNullElse(fileName, “Unknown Source”));

Or, optionally, we can use an Optional idiom as well.  

builder.append(Optional.ofNullable(fileName).orElse(“Unknown Source”));

All of them are just fine, but however, I like the new method, Objects.requireNonNullElse(), which makes it more descriptive, and thus the code becomes more readable as well as shorter. 

Repeating strings

In many cases, you want to repeat the same string multiple times.

I found a similar example in the code base, which is as follows: 

var padRequired = 5;
for (int i = 0; i < padRequired; i++) {

The above code can be rewritten as follows: 


That’s all for today. 

As I continue refactoring the code, I will keep sharing the newer idioms!

Also, I would love to get some feedback from you all. 

The post A Minor But Useful Refactoring Technique That Would Reduce Your Code Footprint (Part 1) appeared first on foojay.