87

If I have to design a Utility class( such as ByteUtils or StreamUtils or StringUtils), what is the best design choice for them.

  • Should they be static classes (as I won't have any states to store)
  • Should they be non-static classes ( so that if the objects are not used, they will be gc'd)

PS: By static class, I meant a class with static methods(and not the inner static class)

Please give advice on design choices for this ?

3
  • 7
    You need to reword this question. Outer level classes cannot be static in Java. They can have nothing but static methods. Not the same thing.
    – user207421
    Aug 16, 2011 at 10:13
  • Yes. you are correct. I meant a class with methods being static
    – nibin012
    Aug 16, 2011 at 13:30
  • While your examples (Byte, String, Stream) should be fairly small, if you happen to have a 1k LOC in EJB that uses a mapper utility that has static methods, testing of that EJB becomes quite difficult. Jan 14, 2014 at 17:15

10 Answers 10

81

My utility classes look like this:

// final, because it's not supposed to be subclassed
public final class FooUtil {

    // private constructor to avoid unnecessary instantiation of the class
    private FooUtil() {
    }

    public static int doSomethingUseful() {
    }

    // ...
}

Note that, although this makes the utility methods easily testable, and easily accessible from the outside, it also makes the classes using them hard to unit-test, because it's not easy to mock these utility methods. Having too many of such utility classes can be a sign of a lack of OO design (procedural programming), and can really make the code hard to test.

If you're using a dependency injection framework (Spring, Guice, whatever), it might be a good idea to just make the utility class instantiatable, with non-static methods, and make it an injectable singleton. This way, classes using these utility methods can be tested by mocking the utility object.

7
  • 2
    We can unit test static methods using powermock code.google.com/p/powermock
    – nibin012
    Aug 16, 2011 at 7:53
  • 19
    @nibin012 just because you can, doesn't mean you should. In my project PowerMock is a tool of constant sorrow - it's bad with other tools as it messes with class loaders too much. Jan 14, 2014 at 15:44
  • @jb-nizet could you please provide a minimal example of: > it might be a good idea to just make the utility class instantiatable, with non-static methods, and make it an injectable singleton. It SGTM but I struggle to implement.
    – alexsalo
    Sep 23, 2016 at 22:56
  • 2
    "If you're using a dependency injection framework" - and if not, then it's a bad idea?
    – Line
    Aug 4, 2017 at 21:20
  • you are not unit testing just becauase you use powermocks. In general using a mock like powermock to test a static method you design is probably wrong in some way, as you are overwriting "stateless" methods.
    – Wisienkas
    Dec 7, 2017 at 8:16
55

If it is a general purpose utility, static is IMO better. You stated that you will not have any states to store, so I don't see why should you make it non-static. Declaring it to be static will save memory too.

3
  • 11
    A screw driver doesn't change, it always do the same thing. If the same can be said for your utility class, definitely make it static.
    – Gapton
    Aug 16, 2011 at 7:15
  • 11
    This hold true for all methods that do not rely on the state of the object. Not just utility class methods.
    – Dorus
    Aug 16, 2011 at 8:14
  • 1
    Quite sure making utility class static won't save you enough memory to do something remarkable. So not the true reason, I'd say
    – Farid
    Oct 18, 2021 at 18:16
24

Just because something can be static, doesn't mean it should be static.

There is another consideration to all this: mocking. It's harder to mock static methods in your tests than it is to mock the behaviour of an instance of a class.

Talk of unnecessary heap allocations and GCing of objects smacks of premature optimisation to me. The JVM will do a pretty good job at optimising away this sort of issue.

12

The simplest way to define a Utility class is as an enum with no instances

public enum Utility {;
     public static int utilityMethod(int x) { /* ... */ }
}

A utility class shouldn't have any state or have minimal state so you shouldn't worrying about GCs.

You can have other stateful classes for specific purposes like Builder, Factory, you can create the object as desired and discard it when you have finished.

12
  • 1
    I assume you don't mean a static nested class. This avoids needing to remember to create the private constructor to prevent people accidentally creating an instance of the utility class. Enums are final by default. Aug 16, 2011 at 7:34
  • 1
    In Java, enum can have mutable fields, implement interfaces and abstract methods so they are much more than just constants. ;) Aug 16, 2011 at 9:38
  • 4
    @PeterLawrey, while this is true, it smacks of over engineering to me. Since 1996, I can count a sum total of zero times that I've seen someone accidentally instantiate a class meant to be a simple static utility. Providing such protections is silly IMO, because the consequences of instantiating something like this is you notice immediately that it won't work. Putting in an enum into the mix however changes how the tired engineer at 3am hopped on caffeine will read the thing and make him wonder for a moment what's going on. It's just not a common idiom. Use class and be happy.
    – user4229245
    Apr 15, 2015 at 12:53
  • 4
    The primary point I'm truly making here is that when you use an enum, you are telegraphing to the reader that there is a reason for enumeration hidden in its design. There isn't. You're only trying to make it easier than putting in a final and private constructor, neither of which are an issue IMO. That's an unusual idiom. And you saw someone trying to instantiate a class of utility static methods? Does this matter? If someone sees the class as supplying the methods they need, they know what they are----why would they instantiate it? And what happens if they did? Not much.
    – user4229245
    Apr 15, 2015 at 14:06
  • 4
    I think we have been needing to question some of our over-protective thinking for quite some time now. Freaking out over gotos, avoiding multiple returns, instantiation protection, etc., etc., there is really very limited up side to all of this. However what is worth protecting is the readability of the code. Always try to remain as close to the no-brainer category as you can.
    – user4229245
    Apr 15, 2015 at 14:08
6

Its good to make the class as non-static with a private constructor:

  • if we make the class static then class will be loaded when the application is deployed, if it is non-static then the class will be loaded when there is a call to one of its static methods
  • creating a private constructor will avoid instantiating the class
1
  • Then how to use this class? NonStatic with private constrctr Jun 17, 2019 at 8:44
4

Usually utility classes contain static methods and no attributes, this approach makes it easier to use their methods without instantiating the class. Hope this helps.

3

If you can make them static, then definitely do so!

In other words, if they don't have state, they should be static.

3
  • 1
    I've coded in projects that followed that principle. "If you can", that is. Testing was nightmarish thanks to that. And PowerMock made matters worse, due to it's classloader magic that collided with other tools in never-easy-to-figure-out ways. Downvoted. Jan 14, 2014 at 17:14
  • 1
    @LIttleAncientForestKami, I agree in general with the "if you can". However, I think what Petar was saying was "if there's no reason to use anything other than static then use static" (or less clumsy words to that effect). At least that's the meaning I took from his statement. IOW, "If you don't need an instance, then don't make an instance just to have one." Again, my take on his statement.
    – user4229245
    Apr 15, 2015 at 18:42
  • it helps with refactoring and readability to know that a method does not mutate the state of objects of that class
    – Kirby
    Feb 7 at 19:00
3

Well, if you have no state to store then there is nothing to GC, so I would go with static, that way you avoid any unnecessary heap allocations and GC.

2

Pure utility classes should usually be static. When you have a class with well-defined input and output, no side effects and no state, then by definition it should be a static class.

In general, don't add complexity (dependency injection in this case) before it's necessary and there's a benefit in doing it.

0

Nobody here mention that static utility methods are not extensible. You cannot override them. You cannot take advantage of OOP (particularly polymorphysm, which is most powerful feature of OOP). That leads to code duplication.

P.S. I found this article very helpful. http://www.yegor256.com/2014/05/05/oop-alternative-to-utility-classes.html

10
  • Define "extensible"... there's nothing preventing you from making overloads in your own tool classes that call the existing tools (not a big difference from subclassing/overloading IMO), and if you want to prevent code duplication, you can always use generics to allow a wider range of types to be handled by your tool function.
    – Nyerguds
    May 15, 2018 at 8:13
  • 1
    That article seems to go for a "use objects for the sake of it being OOP" mindset, which IMO is just memory pollution. Not only does it give extra work to the GC, but since object references can be stored, all object creation holds a risk of creating memory leaks. Not worth it.
    – Nyerguds
    May 15, 2018 at 8:17
  • Not sure why this is downvoted. A good article that summarizes why this is the better option: vojtechruzicka.com/avoid-utility-classes
    – Pratik
    Jun 9, 2020 at 19:56
  • @Nyerguds you're absolutely wrong about extra work for the GC. The usual way to do this is to have a singleton (a static getInstance() method) with a private constructor.
    – Pratik
    Jun 9, 2020 at 19:57
  • @Pratik Then it's memory pollution, since it keeps those objects indefinitely.
    – Nyerguds
    Jun 11, 2020 at 0:14

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