1

Is it a right/recommended practice to add a private no-args constructor (which does nothing) for a class with only static utility methods and no instance variable (completely stateless)?

My reasoning for same is, i want to avoid any client using this class by instantiating it and always want this class's methods to be accessed in static fashion. Private constructor helps me adding this restriction on my utility classes.

Also i am defining my static classes as final, to avoid any client extending them; is it a right practice?

Bug Finder
  • 11
  • 2
  • 1
    Yes. It's described in Item 4 of *Effective Java 2nd Ed*, "Enforce noninstantiability with a private constructor". – Andy Turner May 06 '17 at 21:38
  • "Also i am defining my static classes as final" If you've got a private no-arg ctor (and no other ctors) it's redundant, but it doesn't hurt. – Andy Turner May 06 '17 at 21:39
  • What you are describing is called a "Utility Class", and yes, it's perfectly fine to do so. There would be no need to ever have an instance of such a class. – Michael Markidis May 06 '17 at 21:40
  • http://stackoverflow.com/questions/1844355/java-static-class – qrius May 06 '17 at 21:43
  • Utility classes have a big drawback: you cannot apply *dependency injection* to the classes using them. This make the using classes less flexible and hard to write *unit test* for them. – Timothy Truckle May 06 '17 at 21:46
  • @TimothyTruckle it's easy to write unit tests for the utility classes: they've got no state, so you have to inject all the dependencies anyway. It's writing unit tests for classes *using* the utility classes which is harder. – Andy Turner May 06 '17 at 22:06
  • @AndyTurner: That was not my claim. It's harder to write UnitTest for **classes using** Utility classes. – Timothy Truckle May 06 '17 at 22:12

1 Answers1

2

Yes. To make sure no one instantiating it is best practice to define an private no args constructor which throw an IllegalStateException. For example, for StringUtils class I would define the following constructor:

private StringUtils() {
    throw new IllegalStateException("StringUtils class");
}