Oct 22, 2018

Why should utility classes be avoided?

Generally, Utils and Helper type classes should be avoided. More often than not, you will find that what you may think is a utility method, is actually a rather specific method that probably belongs in a class of its own. However, there will be domain specific cases where Util-like classes (classes which group related useful methods) are valid entities.

Utility classes can violate the principles that compose a good object-oriented design. In a good object-oriented design, most classes should represent a single thing and all of it's attributes and operations. If you are operating on a thing, that method should probably be a member of that thing.

You need to think about your design and determine where it makes the most sense to put the methods. Usually, it's as operations inside of a class. Don't use utility classes where static or instance methods in a domain class would be a better solution. For example, consider if methods in an abstract base class or an instantiable helper class would be a better solution.

However, there are times when you can use utility classes to group a number of methods together - an example being the java.util.Collections class which provides a number of utilities that can be used on any Java Collection. These aren't specific to one particular type of Collection, but instead implement algorithms that can be used on any Collection.

When you do use a utility class, don't just throw random methods into it - organize the methods by purpose and functionality, group them into classes in a way that will make it easy for developers to find them. Design the static utility methods to be general and reusable. Make sure that they are stateless;