一个类只有静态字段和方法是坏的做法吗? [英] Is it bad practice for a class to have only static fields and methods?
问题描述
我有一个只包含的静态成员变量和静态方法的类。
I have a class that consists only of static member variables and static methods. Essentially, it is serving as a general-purpose utility class.
一个类只包含静态成员变量和静态方法是不好的做法吗? strong>
Is it bad practice for a class to contain only static member variables and static methods?
推荐答案
不,我不这么认为。更糟糕的做法是拥有一个充满实例方法的类,它实际上不依赖于特定的实例。使它们静态,告诉用户他们打算如何使用。此外,您可以避免不必要的实例化。
No, I don't think so at all. It is worse practice to have a class full of instance methods which don't actually depend on a particular instance. Making them static tells the user exactly how they are intended to be used. Additionally, you avoid unnecessary instantiations this way.
编辑:作为一个事后,一般来说,我认为它很好避免使用语言功能只是因为那就是Java做的方式。我记得我的第一份工作,我有一个充满了静态实用程序方法和一个高级程序员告诉我,我没有充分利用Java的OO力量,使我的所有方法全局。她6个月后不在球队。
As an afterthought, in general I think its nice to avoid using language features "just because", or because you think that that is the "Java way to do it". I recall my first job where I had a class full of static utility methods and one of the senior programmers told me that I wasn't fully harnessing the OO power of Java by making all of my methods "global". She was not on the team 6 months later.
这篇关于一个类只有静态字段和方法是坏的做法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!