Member-only story

Effective Java! Utility Classes!

Kyle Carter
2 min readDec 24, 2020

Time for chapter four of our Effective Java review! Today is a quick and easy chapter.

Today we are talking about utility classes. As the author points out these classes can often feel like an anti-pattern and a way of getting around using proper objects. That being said they definitely have their purpose in the world, especially in Java. So let’s consider some of the places that utility classes could be beneficial:

  • For grouping actions on primitive objects. ie java.lang.Math, java.util.Arrays
  • For grouping actions on classes you don’t own. This is similar to the above but in this case its on object that you may not have access to change. LocalDateUtils is something I have seen before. This is something that extension functions can solve in a much cleaner manner in languages such as Kotlin.
  • They can also be a home for factory methods such as in java.util.Collections

So we can see there are some use cases where this is useful so how do we accomplish it? What it really comes down to is not to forget to account for making it not instantiable. We know that even if you don’t include a constructor Java will add a default no-args constructor.

The first method is making the class an abstract class. This does indeed make the class not able to be instantiated directly but doesn’t really accomplish what it is after. The reasoning is two fold. First, a user of the class can derive from that abstract class and make the child class can be…

--

--

Kyle Carter
Kyle Carter

Written by Kyle Carter

I'm a software architect that has a passion for software design and sharing with those around me.

No responses yet