Is it bad practice for a class to have only static fields and methods?

后端 未结 14 631
予麋鹿
予麋鹿 2020-11-30 03:05

I have a class that consists only of static member variables and static methods. Essentially, it is serving as a general-purpose utility class.

Is i

相关标签:
14条回答
  • 2020-11-30 03:25

    It's perfectly reasonable. In fact, in C# you can define a class with the static keyword specifically for this purpose.

    0 讨论(0)
  • 2020-11-30 03:25

    The Collections class in Java SDK has static members only.

    So, there you go, as long as you have proper justification -- its not a bad design

    0 讨论(0)
  • 2020-11-30 03:27

    Just don't get carried away with it. Notice that the java.lang.Math class is only about math functions. You might also have a StringUtilities class which contains common string-handling functions which aren't in the standard API, for example. But if your class is named Utilities, for example, that's a hint that you might want to split it up.

    0 讨论(0)
  • 2020-11-30 03:27

    Utility methods are often placed in classes with only static methods (like StringUtils.) Global constants are also placed in their own class so that they can be imported by the rest of the code (public final static attributes.)

    Both uses are quite common and have private default constructors to prevent them from being instantiated. Declaring the class final prevents the mistake of trying to override static methods.

    If by static member variables you did not mean global constants, you might want to place the methods accessing those variables in a class of their own. In that case, could you eleborate on what those variables do in your code?

    0 讨论(0)
  • 2020-11-30 03:27

    This is typically how utility classes are designed and there is nothing wrong about it. Famous examples include o.a.c.l.StringUtils, o.a.c.d.DbUtils, o.s.w.b.ServletRequestUtils, etc.

    0 讨论(0)
  • 2020-11-30 03:29

    I wouldn't be concerned over a utility class containing static methods.

    However, static members are essentially global data and should be avoided. They may be acceptable if they are used for caching results of the static methods and such, but if they are used as "real" data that may lead to all kinds of problems, such as hidden dependencies and difficulties to set up tests.

    0 讨论(0)
提交回复
热议问题