Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Utility classes are evil? [closed]

I saw this question: If a "Utilities" class is evil, where do I put my generic code?

And I thought, why are utility classes evil?

Let’s say I have a domain model that is dozens of classes deep. I need to be able to xml-ify instances. Do I make a toXml method on the parent? Do I make a MyDomainXmlUtility.toXml helper class? This is a case where the business need spans the entire domain model -- does it really belong as an instance method? What about if there are a bunch of auxiliary methods on the XML functionality of the application?

like image 915
hvgotcodes Avatar asked Jul 27 '10 00:07

hvgotcodes


People also ask

Are utility classes bad practice?

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.

Is a Helper class a code smell?

A Helper class is a lesser known code smell where a coder has identified some miscellaneous, commonly used operations and attempted to make them reusable by lumping them together in an unnatural grouping.

When should you create a utility class?

A utility class reverses the idea of object-oriented programming. When you come to the point that you need a new method you usually add it to the class with the highest cohesion.


1 Answers

Utility classes aren't exactly evil, but they 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 its attributes and operations. If you are operating on a thing, that method should probably be a member of that thing.

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.

Really, what you need to do is 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. However, sometimes, it is indeed as a utility class. When you do use a utility class, however, don't just throw random methods into it, instead, organize the methods by purpose and functionality.

like image 186
Thomas Owens Avatar answered Oct 18 '22 06:10

Thomas Owens