java – 在什么情况下是静态方法一个好的做法?


Should private helper methods be static if they can be static
Should all methods be static if their class has no member variables


>他们违反了OO原则。 (他们



我认为静态方法是好的,当他们是私人的,或者当他们是“效用”的方法 – 例如。做字符串转义。问题出现时,你使用静态方法的东西,你想能够模拟出来或在测试中替换。工厂方法也可以是有用的,虽然依赖注入通常是一个更好的方法 – 再次,它部分取决于您是否想要能够替换测试中的功能。

至于不是“OO” – 不是你在一般的OO语言写的一切都必须是“纯粹的”OO。有时非OO路由只是更务实,导致更简单的代码。 Eric Lippert有一个伟大的博客文章,这不幸的是我现在找不到。但是,在this post有一个意见是相关的。它谈论扩展方法而不是静态方法,但原理是一样的。

Extension methods are often criticized
as being “not OOP enough”. This seems
to me to be putting the cart in front
of the horse. The purpose of OOP is to
provide guidelines for the structuring
of large software projects written by
teams of people who do not need to
know the internal details of each
other’s work in order to be
productive. The purpose of C# is to be
a useful programming language that
enables our customers to be productive
on our platforms. Clearly OOP is both
useful and popular, and we’ve
therefore tried to make it easy to
program in an OOP style in C#. But the
purpose of C# is not “to be an OOP
language”. We evaluate features based
on whether they are useful to our
customers, not based on whether they
conform strictly to some abstract
academic ideal of what makes a
language object-oriented. We’ll
happily take ideas from oo,
functional, procedural, imperative,
declarative, whatever, so long as we
can make a consistent, useful product
that benefits our customers.


转载注明原文:java – 在什么情况下是静态方法一个好的做法?