0

I have read several questions regarding when to use a utility class or any class that doesn't have a state associated with it.

My question is what is the best implementation once you have decided to use a utility class? A static class, a normal class with private constructor and only static methods (similar to java's math class), or an alternative?

I understand that this will probably depend on my specific situation but I do not have one and was looking for more general guidelines or advantages and disadvantages to each implementation method.

1
  • I wouldn't do that if I were you, unless you're not looking forward to OOP.
    – yoda
    Sep 27, 2011 at 12:42

3 Answers 3

3

What is the best implementation once you have decided to use a utility class?

Exactly what you proposed. Create a private constructor, make the class final and implement static utility methods. In such cases, there's no need to make things more complex.

Of course, you must be careful to not falling back into imperative/procedural programming style... just one opinion.

0

IMHO:

For Utilty Classes for little everyday Problems like Converting Stuff etc is a static class with no constructor the best implementation. Very Handy to access:

Utils.ConvertDateToCake();

My Utility Classes which need an Constructor are implemented as Singletons. So you can access them like this:

DatabaseUtils.getInstance().DoSomething();
0

Utility classes are pure evil in OOP. Check this blog post for better explanation: http://www.yegor256.com/2014/05/05/oop-alternative-to-utility-classes.html

In a nutshell, utility classes bring procedural programming into OOP, making your code less testable, less maintainable/readable, and slower (!).

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