Are global static classes and methods bad?

前端 未结 10 1249
予麋鹿
予麋鹿 2020-12-02 13:36

It\'s generally agreed upon that relying heavily on global stuff is to be avoided. Wouldn\'t using static classes and methods be the same thing?

相关标签:
10条回答
  • 2020-12-02 14:08

    As an addition to whatever else is said, final static variables are just fine; constants are a good thing. The only exception to that is when/if you should just move them to a properties file, to be easier to change.

    0 讨论(0)
  • 2020-12-02 14:08

    Mutable static variables are bad because they're just global state. The best discussion I know of about this is here, under the heading "Why Global Variables Should Be Avoided When Unnecessary".

    Static methods have several drawbacks that often make them undesirable - the biggest one being that they cannot be used polymorphically.

    0 讨论(0)
  • 2020-12-02 14:09

    Static methods are used to implement traits in Scala. In C#, extension methods (which are static) fulfill that role in part. That could be seen, as the DCI proponents state, as a "higher order form of polymorphism".

    Also, static methods can be used to implement functions. This is what F# uses to implement modules. (And also VB.NET.) Functions are useful for (unsurprisingly) functional-programming. And sometimes they're just the way something should be modeled (like the "functions" in the Math class). Again, C# comes close here.

    0 讨论(0)
  • 2020-12-02 14:11

    static doesn't necessarely mean global. Classes and members can be static private, hence only applying to the specific class. That said, having too many public static members instead of using appropriate ways to pass data (method calls, callbacks, etc.) is generally bad design.

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