Skip to content
Advertisement

Naming convention for utility classes in Java

When writing utility classes in Java, what are some good guidelines to follow?

Should packges be “util” or “utils”? Is it ClassUtil or ClassUtils? When is a class a “Helper” or a “Utility”? Utility or Utilities? Or do you use a mixture of them?

The standard Java library uses both Utils and Utilities:

  • javax.swing.Utilities
  • javax.print.attribute.AttributeSetUtilities
  • javax.swing.plaf.basic.BasicGraphicsUtils

Apache uses a variety of Util and Utils, although mostly Utils:

  • org.apache.commons.modeler.util.DomUtil
  • org.apache.commons.modeler.util.IntrospectionUtils
  • org.apache.commons.io.FileSystemUtils
  • org.apache.lucene.wordnet.AnalyzerUtil
  • org.apache.lucene.util.ArrayUtil
  • org.apache.lucene.xmlparser.DOMUtils

Spring uses a lot of Helper and Utils classes:

  • org.springframework.web.util.UrlPathHelper
  • org.springframework.core.ReflectiveVisitorHelper
  • org.springframework.core.NestedExceptionUtils
  • org.springframework.util.NumberUtils

So, how do you name your utility classes?

Advertisement

Answer

Like many such conventions, what’s important is not so much what convention you use, as that you use it consistently. Like, if you have three utility classes and you call them CustomerUtil, ProductUtils, and StoreUtility, other people trying to use your classes are going to constantly get confused and type CustomerUtils by mistake, have to look it up, curse you a few times, etc. (I heard a lecture on consistency once where the speaker put up a slide showing an outline of his speech with three main points, labeled “1”, “2nd”, and “C”.)

Never ever ever make two names that differ only in some subtlety of spelling, like having a CustomerUtil and a CustomerUtility. If there was a good reason to make two classes, then there must be something different about them, and the name should at least give us a clue what that difference is. If one contains utility functions related to name and address and the other contains utility functions related to orders, then call them CustomerNameAndAddressUtil and CustomerOrderUtil or some such. I regularly go nuts when I see meaningless subtle differences in names. Like just yesterday I was working on a program that had three fields for freight costs, named “freight”, “freightcost”, and “frght”. I had to study the code to figure out what the difference between them was.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement