3

I want to know when is considered a bad practice to have a class with only static methods and variables, and what alternatives exists to avoid the practice.

I understand that they are necessary for all the cases when you need functionality but you can't or don't need an object's instance. Nevertheless I was wondering if this situations aren't the result of bad practices o bad design decisions.

Thanks

Augusto Altman Quaranta
  • 1,526
  • 1
  • 21
  • 32
  • 1
    One alternative is `enum`s. You get real singleton `Object` instances. But they're not cheap memory-wise. – Mena Sep 05 '14 at 18:20
  • It is always bad practice and the actual root of problem is in abscence of it's real use. The only two reasons I use static fields are 1) for storing constants (in .NET due to technical reasons it's better than using consts), 2) for private methods not using object instance. Singletons are almost always handled by IoC containers. Take a look at http://stackoverflow.com/questions/25617276/why-best-practices-vary-for-static-classes-in-c-sharp-and-java – Valentin P. Sep 05 '14 at 19:27

3 Answers3

4

A common alternative is to use a singleton or an instance class where you have just one instance.

This is preferable as it is easier to test, and inject different functionality.

If your class has no fields

  • Use an enum class with no instances as a utility class.
  • where possible, move the static methods to a class which appears as one of the arguments.
  • use a stateless singleton if it need to implement an interface.
Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
2

There is no problem with having files with only final static variables, it's just a way of grouping constants.

However, the typical helper/utils classes with only static methods tend to provoke bad OO designs or they are symptoms of it.

A common case it's a DateUtil class, the class Date it's so bad designed that you need facilities to use it. Although it's tempting to create yours, it's better to use a proper Date API (like Yoda Time) or the new Date API.

So, try to avoid this kind of classes and put these methods close to the objects which are related to.

polypiel
  • 2,321
  • 1
  • 19
  • 27
0

I find it best to try and only use static methods and values in the way that the native java packages do. Boiler plate code and purely functional things. EX: Trig functions, parsing/converting data, etc.

new Objekt
  • 414
  • 3
  • 8