什么时候方法应该是静态的? [英] When should a method be static?

查看:21
本文介绍了什么时候方法应该是静态的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

另外,静态方法相对于实例方法有什么性能优势吗?

In addition, are there any performance advantages to static methods over instance methods?

我最近遇到了以下问题:http://www.cafeaulait.org/course/week4/22.html :

I came across the following recently: http://www.cafeaulait.org/course/week4/22.html :

什么时候方法应该是静态的?

When should a method be static?

  1. 既不读取也不写入实例字段
  2. 独立于对象的状态
  3. 接受参数的数学方法,将算法应用于那些参数,并返回一个值
  4. 代替构造函数的工厂方法

我对 Stack Overflow 社区对此的反馈非常感兴趣.

I would be very interested in the feedback of the Stack Overflow community on this.

推荐答案

当方法不是实例的一部分时,将它们设为静态.不要担心微观优化.

Make methods static when they are not part of the instance. Don't sweat the micro-optimisations.

您可能会发现有很多私有方法可能是静态的,但您总是从实例方法(或彼此调用)调用.在这种情况下,它并不重要.但是,如果您希望真正能够测试您的代码,并且可能从其他地方使用它,您可能需要考虑在不同的、不可实例化的类中创建这些静态方法.

You might find you have lots of private methods that could be static but you always call from instance methods (or each other). In that case it doesn't really matter that much. However, if you want to actually be able to test your code, and perhaps use it from elsewhere, you might want to consider making those static methods in a different, non-instantiable class.

这篇关于什么时候方法应该是静态的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆