使用很多静态方法是一件坏事吗? [英] Is using a lot of static methods a bad thing?
问题描述
当类中不需要跟踪内部状态时,我倾向于将类中的所有方法声明为静态的.例如,如果我需要将A转换为B并且不依赖于可能变化的某些内部状态C,则可以创建一个静态转换.如果要调整内部状态C,则添加一个构造函数以设置C,并且不要使用静态变换.
I tend to declare as static all the methods in a class when that class doesn't require to keep track of internal states. For example, if I need to transform A into B and don't rely on some internal state C that may vary, I create a static transform. If there is an internal state C that I want to be able to adjust, then I add a constructor to set C and don't use a static transform.
我阅读了各种建议(包括关于StackOverflow的建议),而不是过度使用静态方法,但是我仍然无法理解上述经验法则的错误所在.
I read various recommendations (including on StackOverflow) NOT to overuse static methods but I still fail to understand what it wrong with the rule of thumb above.
这是一种合理的方法吗?
Is that a reasonable approach or not?
推荐答案
有两种常见的静态方法:
There are two kinds of common static methods:
- 安全"静态方法将始终为相同的输入提供相同的输出.它不会修改全局变量,也不会调用任何类的任何不安全"静态方法.本质上,您使用的是有限的函数式编程-不用担心,它们很好.
- 不安全"的静态方法会更改全局状态或一个全局对象的代理或某些其他不可测试的行为.这些都是过程编程的回弹,应尽可能进行重构.
不安全"静态变量有几种常见用法(例如,在Singleton模式中),但请注意,尽管您将其称为漂亮名称,但您只是在对全局变量进行突变.在使用不安全的静态变量之前,请仔细考虑.
There are a few common uses of "unsafe" statics -- for example, in the Singleton pattern -- but be aware that despite any pretty names you call them, you're just mutating global variables. Think carefully before using unsafe statics.
这篇关于使用很多静态方法是一件坏事吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!