You should Avoid the Use of Util Class

Ahmad Kamil Almasyhur
2 min readMar 31, 2019

--

As object oriented believer, you should already believe that every object should have name, attributes and behavior. As an SOLID principles, you should understand that, object should be small and do one things, and a class should have one, and only one, reason to change. Then, why you should avoid using util class?

source: https://www.tomdalling.com

What is Utility Classes?

Utility Classes are classes that have only static methods that perform some operation on the objects passed as parameters. Such classes typically have no state.

Utility Class is usually declared final, so it cannot be subclassed. The constructor is declared as private with an explaining comment and even possible exception when invoked. With a private constructor declared, the default one is not generated and class cannot be instantiated by other classes.

Problem when using Utility Classes

Tight Coupling

The main problem is that a class depending on a static method from a Utility Class has tight coupling. You are using a specific external dependency, not an abstraction. There is no way to switch that dependency under various circumstances. Usually, you would be able to provide a subclass of that dependency instead or another dependency implementing the interface. You lose that flexibility completely.

Single Responsibility

A class using Utility Class is responsible not only for its original role, but also for obtaining its dependencies. Another problem is that existing Utility Classes have tendencies to rot. Usually, such classes are created from a code, which has no better or proper place to be. Over time, if you are not very strict, these classes tend to accumulate more and more code, which may be not so related to the original methods. The class would lose its original single responsibility and become a jack-of-all-trades. Known as God Class.

--

--