Java什么情况下使用静态方法,java – 在什么情况下是静态方法一个好的做法?...

静态方法不难自己测试。问题是,其他调用静态方法的代码很难测试,因为你不能替换静态方法。

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

至于不是“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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值