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

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

问题描述

此外,静态方法相对于实例方法是否具有性能优势?

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. 代替构造函数使用的工厂方法
  1. Neither reads from nor writes to instance fields
  2. Independent of the state of the object
  3. Mathematical methods that accept arguments, apply an algorithm to those arguments, and return a value
  4. Factory methods that serve in lieu of constructors

我对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天全站免登陆