Friends of OpenJDK Today

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

October 20, 2022

Author(s)

  • Avatar photo
    A N M Bazlur Rahman

    A N M Bazlur Rahman is a Software Engineer with over a decade of specialized experience in Java and related technologies. His expertise has been formally recognized through the prestigious ... Learn more

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 will 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<>();
    favoriteRules.add(RuleType.RULE_ONE);
    favoriteRules.add(RuleType.RULE_TWO);
    favoriteRules.add(RuleType.RULE_ETC);
    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:

Set.of(1,2,3,4,5);

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. 

Example:

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

There are multiple ways to turn it into oneliners. 

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

//Or

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++) {
  builder.append("&nbsp;");
}  

The above code can be rewritten as follows: 

builder.append("&nbsp;".repeat(padRequired));

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. 

Related Articles

View All

Author(s)

  • Avatar photo
    A N M Bazlur Rahman

    A N M Bazlur Rahman is a Software Engineer with over a decade of specialized experience in Java and related technologies. His expertise has been formally recognized through the prestigious ... Learn more

Comments (0)

Your email address will not be published. Required fields are marked *

Highlight your code snippets using [code lang="language name"] shortcode. Just insert your code between opening and closing tag: [code lang="java"] code [/code]. Or specify another language.

Save my name, email, and website in this browser for the next time I comment.

Subscribe to foojay updates:

https://foojay.io/feed/
Copied to the clipboard