如果私有帮助方法可以是静态的,那么它们应该是静态的 [英] Should private helper methods be static if they can be static

查看:103
本文介绍了如果私有帮助方法可以是静态的,那么它们应该是静态的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个设计用于实例化的类。我在类中有几个私有的helper方法,它们不需要访问任何类成员,并且只对它们的参数进行操作,返回结果。

Let's say I have a class designed to be instantiated. I have several private "helper" methods inside the class that do not require access to any of the class members, and operate solely on their arguments, returning a result.

public class Example {
   private Something member;

   public double compute() {
       double total = 0;
       total += computeOne(member);
       total += computeMore(member);
       return total;         
   }

   private double computeOne(Something arg) { ... }
   private double computeMore(Something arg) {... } 
} 

是否有任何特殊原因指定 computeOne computeMore 作为静态方法 - 或者任何特殊原因没有?

Is there any particular reason to specify computeOne and computeMore as static methods - or any particular reason not to?

将它们保持为非静态,即使是最简单的也是最容易的虽然它们当然可以是静态的而不会造成任何问题。

It is certainly easiest to leave them as non-static, even though they could certainly be static without causing any problems.

推荐答案

我更喜欢这样的辅助方法是 private静态;这将使读者清楚他们不会修改对象的状态。我的IDE也会以斜体显示对静态方法的调用,所以我知道这个方法是静态的而不需要查看签名。

I prefer such helper methods to be private static; which will make it clear to the reader that they will not modify the state of the object. My IDE will also show calls to static methods in italics, so I will know the method is static without looking the signature.

这篇关于如果私有帮助方法可以是静态的,那么它们应该是静态的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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