Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

I sometimes create 'Util' classes which primarily serve to hold methods and values that don't really seem to belong elsewhere. But every time I create one of these classes, I think "uh-oh, I'm gonna regret this later ...", because I read somewhere that it's bad.

But on the other hand, there seem to be two compelling (at least for me) cases for them:

  1. implementation secrets that are used in multiple classes within a package
  2. providing useful functionality to augment a class, without cluttering its interface

Am I on the way to destruction? What you say !! Should I refactor?

share|improve this question

closed as not constructive by Walter, Jarrod Roberson, gnat, Yusubov, ChrisF Nov 8 '12 at 23:00

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.If this question can be reworded to fit the rules in the help center, please edit the question.

7  
Stop using Util in your classes' names. Problem solved. –  Yannis Rizos Nov 8 '12 at 20:35
    
@Yannis haha, nice one. If only it were so easy. –  Matt Fenwick Nov 8 '12 at 20:36
2  
@MattFenwick Yannis has a good point. Naming a class SomethingUtil is a bit lazy and just obscures the true purpose of the class - same with classes named SomethingManager or SomethingService. If that class has a single responsibility it should be easy to give it a meaningful name. If not, that's the real problem to deal with... –  MattDavey Nov 8 '12 at 20:43
1  
If you create multiple *Util classes separated by which kind of object they manipulate, then I think it's fine. I don't see any problem with having a StringUtil, ListUtil, etc. Unless you are in C# then you should use extention methods. –  marco-fiset Nov 8 '12 at 21:44
4  
I often have sets of functions that are used for related purposes. They don't really map well to a class. I don't need an ImageResizer class, I just need a ResizeImage function. So I'll put related functions into a static class like ImageTools. For functions that aren't in any sort of grouping yet, I do have a Util static class to hold them, but once I have a few that are related enough to each other to fit in one class, I'll move them. I see no better OO way to handle this. –  Philip Nov 8 '12 at 21:55

5 Answers 5

It's perfectly acceptable to have util classes, though I prefer the term ClassNameHelper. The .NET BCL even has helper classes in it. The most important thing to remember, is to thoroughly document the classes purpose, as well as each individual helper method, and to make it high quality maintainable code.

And don't get carried away with helper classes.

share|improve this answer

Util classes are not cohesive and are, generally bad design, because a class has to have a single reason to change (Single Responsability Principle).

Yet, I've seen "util" classes in the very Java API, like: Math, Collections and Arrays.

These are, in fact, utility classes but all their methods are related to a single theme, one has mathematical operations, on has methods for manipulating collections and the other for manipulating arrays.

Try not no have totally unrelated methods in an utility class. If that is the case, chances are you can as well put them elsewere where they really belong.

If must have util classes then try them to be separated by theme like Java's Math, Collections and Arrays. It, at least, shows some intention of design even when they are just namespaces.

I for one, always avoid utility classes and never have had the need to create one.

share|improve this answer
    
Thanks for the response. So, even if the util classes are package-private, they're still a design smell? –  Matt Fenwick Nov 8 '12 at 21:07
    
not everything belongs in a class though. if your are stuck with a language that insists that it does then utils classes will happen. –  jk. Nov 8 '12 at 22:14
1  
Well, utility classes don't have a design principle to let you know how many methods is too much, since there's no cohesiveness to begin with. How could you know how to stop ? After 30 methods ? 40 ? 100 ? OOP principles, in the other hand give you an idea of when a method doesn't belong to a particular class, and when the class is doing too much. That's called cohesiveness. But as I told you in my answer, the very people who designed Java used utility classes. You can't do it too. I don't create utility classes and haven't been on a situation when something doesn't belong in a normal class. –  user61852 Nov 8 '12 at 22:18
    
Utils classes are usually not classes they are just namespaces containing a bunch of, usually pure, functions. Pure functions are as cohesive as you can get. –  jk. Nov 8 '12 at 22:21
1  
@jk I meant Utils... By the way coming up with a names like Math or Arrays shows at least some intention of design. –  user61852 Nov 8 '12 at 22:35

Modern OO design accepts that not everything is an object. Some things are behaviors, or formulae, and some of those don't have state. It's good to model these things as pure functions to get the benefit of that design.

Java and C# (and others) require you make a util class and jump through that hoop to do it. Annoying, but not the end of the world; and not really troublesome from a design perspective.

share|improve this answer
    
Yeah, that's sort of what I was thinking. Thanks for the response! –  Matt Fenwick Nov 8 '12 at 21:41
    
Agreed, although it should be mentioned that .NET now offers extension methods and partial classes as an alternative to this approach. If you take this item to its extreme, you end up with Ruby mixins -- a language that has little need for utility classes. –  neontapir Nov 8 '12 at 21:49
2  
@neontapir - Except the implementation of extension methods basically forces you to make a util class with the extension methods... –  Telastyn Nov 8 '12 at 22:03
    
True. There are two places where Util classes hinder, one is in the class itself and the other is the callsite. By making the methods look like they exist on the enhanced object, extension methods address the callsite issue. I agree, there is still the issue of the Util class's existance. –  neontapir Nov 8 '12 at 22:07

Never say "Never"

I don't think it's necessarily bad, it's only bad if you do it badly and abuse it.

We All Need Tools and Utilities

For starters, we all use some libraries that are sometimes deemed as almost ubiquitous and must-haves. For instance, in the Java world, Google Guava or some of Apache Commons (Apache Commons Lang, Apache Commons Collections, etc...).

So there clearly is a need for these.

Avoid Hard-Word, Duplication, and Introducing Bugs

If you think about these are pretty much just a very big bunch of these Util classes you describe, except someone went through great lengths to get them (relatively) right, and they've been time-tested and heavily eye-balled by others.

So I'd say the first rule of thumb when feeling the itch to write a Util class is to check that Util class actually doesn't already exist.

The only counter-argument I've seen for that is when you want to limit your dependencies because:

  • you want to limit the memory footprint of your dependencies,
  • or you want to tightly control what developers are allowed to use (happens in obsessive large teams, or when a particular framework is known for having the odd super-crappy class to absolutely avoid somewhere).

But both of these can be tackled by re-packaging the lib using ProGuard or an equivalent, or taking it apart yourself (for Maven users, the maven-shade-plugin offers some filtering patterns to integrate this as part of your build).

So, if it's in a lib and matches your use case, and no benchmarks tells you otherwise, use it. If it varies a bit from what you, extend it (if possible) or extend it, or in the last resort re-write it.

Naming Conventions

However, so far in this answer I called them Utils like you. Don't name them that.

Give them meaningful names. Take Google Guava as a (very, very) good example of what to do, and just imagine that the com.google.guava namespace is actually your util root.

Call your package util, at worst, but not the classes. If deals with String objects and manipulation of string constructs, call it Strings, not StringUtils (sorry, Apache Commons Lang - I still like and use you!). If it does something specific, choose a specific class name (like Splitter or Joiner).

Unit-Test

If you have to resort to writing these utilities, make sure to unit-test them. The good thing about utilities is that they usually are rather self-contained components, which take specific inputs and return specific outputs. That's the concept. So there's no excuse to not unit-test them.

Also, unit-testing will allow you to define and document their API's contract. If tests break, either you changed something the wrong way, or it means you are trying to change your API's contract (or that your original tests were crap - learn from it, and don't do it again).

API Design

The design decision's you'll take for these APIs will follow you a long-time, possibly. So, while not spending hours on writing a Splitter-clone, do be careful about how you approach the issue.

Ask yourself a few questions:

  • Does your utility method warrant a class on its own, or is a static method good enough, if it makes sense for it to be part of a group of similarly useful methods?
  • Do you need factory methods to create objects and make your APIs more readable?
  • Speaking of readability, do you need a Fluent API, builders, etc...?

You want these utils to cover a large breadth of use-cases, to be robust, stable, well-documented, following the principle of least surprise, and to be self-contained. Ideally, each sub-package of your utils, or your whole util package at least, shall be exportable to a bundle for easy re-use.

As usual, learn from giants here:

Yes, many of these have an emphasis on collections and data-structures, but don't tell me that's not where or what for you're usually likely to implement most of your utils, directly or indirectly.

share|improve this answer
    
+1 for If deals with String objects and manipulation of string constructs, call it Strings, not StringUtils –  user61852 Nov 8 '12 at 22:28
    
+1 For API design in .Net, read the book by the architects of .Net. Framework Design Guidelines: Conventions, Idioms, and Patterns for Reusable .NET Libraries –  MarkJ Nov 9 '12 at 6:46
    
Why would you call it Strings instead of StringUtil(s)? Strings to me sounds like a collection object. –  bdrx Sep 9 at 15:22
    
@bdrx: to me a collection object would be either StringsCollectionTypeHere if you want a concrete implementation. Or a more specific name if these strings have specific meaning in the context of your app. For this particular case, Guava uses Strings for its string-related helpers, as opposed to StringUtils in Commons Lang. I find it perfectly acceptable, it just means to me that the classes handles String object or is a general purpose class to manage Strings. –  haylem Sep 12 at 11:37
    
@bdrx: In general NameUtils stuff bug me to no end because if it sits under a clearly labelled package name, I would already know it's a utility class (and if not, would figure it out quickly from looking at the API). It's as annoying to me as people declaring stuff as SomethingInterface, ISomething, or SomethingImpl. I was sort of OK with such artefacts when coding in C and not using IDEs. Today I'd generally have no need for such things. –  haylem Sep 12 at 11:38

I use a two tiered approach. A "Globals" class in a "util" package (folder). For something to go into a "Globals" class or "util" package, it must be:

  1. Simple,
  2. Unchanging,
  3. Not dependent on anything else in your application

Examples that pass these tests:

  • System-wide date and decimal formats
  • Immutable global data, like EARLIEST_YEAR (that the system supports) or IS_TEST_MODE or some-such truly global and unchanging (while the system is running) value.
  • Very small helper methods that work around gaps in your language, framework, or toolkit

Here's an example of a very small helper method, completely independent of the rest of the application:

public static String ordinal(final int i) {
    return (i == 1) ? "1st" :
           (i == 2) ? "2nd" :
           (i == 3) ? "3rd" :
           new StringBuilder().append(i).append("th").toString();
}

Looking at this I can see a bug that 21 should be "21st", 22 should be "22nd", etc. but that's beside the point.

If one of those helper methods grows or becomes complicated it should be moved to its own class in the util package. If two or more helper classes in the util package are related to each other, they should be moved off into their own package. If a constant or helper method turns out to be related to a specific part of your application, it should be moved there.

You should be able to justify why there's no better place for everything you stick in a Globals class or util package and you should clean it periodically using the above tests. Otherwise, you are just creating a mess.

share|improve this answer

Not the answer you're looking for? Browse other questions tagged or ask your own question.