This post is a summary of this artical and this one.
What’s Utility Classes
A utility class is a class filled with static methods. It is usually used to isolate a “useful” algorithm.
FileUtils from Apache Commons;
Iterators from Guava, and
Files from JDK7 are perfect examples of utility classes.
Why Utility Classes
If you have two classes
B, and have a method
f() that both must use, then the most naive approach is to repeat the function as a method in both classes. However, this violates the Don’t repeat yourself (DRY) approach to programming.
The most natural solution is inheritance, but it’s not always beneficial for
B to be subclasses of some parent class. In my case,
A was already a subclass of another class, while
B was not. There was no way to make
B subclasses of a parent class without breaking that other relationship.
The alternative is to define the utility class: a public static class that sits in the global namespace, awaiting anyone to “borrow” them.
They are not bad in themselves, but they do imply relationships between your data that are not explicitly defined. Also, if your static class has any static variables, then
B never really know what they’re getting into when they use it.