有一个不使用实例变量的非静态方法是否有意义? [英] Does it make sense to have a non static method which does not use an instance variable?

查看:112
本文介绍了有一个不使用实例变量的非静态方法是否有意义?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

编译器不允许静态方法调用非静态方法。我理解这样做是因为非静态方法通常最终使用实例变量。

The compiler does not let a static method call a non static method. I understand it does this because a not static method usually ends up using an instance variable.

但是有一个不使用实例的非静态方法是否有意义变量。如果我们的行为不影响或不受实例状态的影响,则不应将此类方法标记为静态。

But does it make sense to have a non static method which does not use an instance variable. If we have a behavior which does not affect or isn't affected by the instance state , shouldn't such a method be marked as static.

推荐答案

很多时候,没有。如果该方法没有触及任何实例状态,则没有理由将其绑定到实例。

Often times, no. If the method doesn't touch any instance state, there's no reason to tie it to an instance.

当然,静态方法不能被继承或覆盖,所以这是一个显而易见的时间,你想要一个不使用实例状态的实例方法。 策略模式就是一个典型的例子。

Of course, static methods can't be inherited or overridden, so that's one obvious time that you would want to have an instance method that doesn't use instance state. The strategy pattern is a classic example of this.

另一个如果这是一个公共API并且您可能想要将该方法绑定到实例状态,将来可能将它绑定到实例的情况是这样的。在这种情况下,使用API​​的人员的向后兼容性问题可能会使(或不可能)将静态方法转换为实例方法。

Another case where you may tie it to an instance anyway is if this is a public API and you imagine that you may want to tie the method to instance state in the future. In that case, backwards compatibility concerns for people who are using your API may make it difficult (or impossible) to turn that static method into an instance method.

这篇关于有一个不使用实例变量的非静态方法是否有意义?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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