简体   繁体   English

class 中的私有 static 方法的优缺点?

[英]private static method in class pros and cons?

Sometimes when writing a class you'll need some helper methods that take care of some simple stuff (change a string in a certain way or do some simple calculations).有时在编写 class 时,您需要一些辅助方法来处理一些简单的事情(以某种方式更改字符串或进行一些简单的计算)。

If helper functionalities are small enough (and not needed by any other class) it makes sense to write a helper method in this class.如果辅助功能足够小(并且任何其他类都不需要),那么在此 class 中编写辅助方法是有意义的。

Now: assuming you'll need no access to any member variables, would it be better do make this method private or private static现在:假设您不需要访问任何成员变量,最好将此方法设为privateprivate static

the following example: just implements a method that checks if a string is not null and contains foo.下面的例子:只实现一个方法来检查一个字符串是否不是null并且包含 foo。

public class SomeClass

...

 public void calculate(String inputString) {
  ...
  boolean foo = getFoo(inputString);
 }

 private (static) boolean getFoo(String inputString) {
  return inputString != null && inputString.contains("foo");
 }

}

Are there pros and cons in making the method static or non-static.制作方法 static 或非静态方法是否有优缺点。 Is there a general do and don't?有一般的做和不做吗?

I would personally make the method static - it makes it clearer that it doesn't depend on the state of the object.我个人会制作方法 static - 它更清楚地表明它依赖于 object 的 state。 That can have knock-on effects in terms of thread safety (although if it were to access static members of the type, you'd need to be careful of that).这可能会在线程安全方面产生连锁反应(尽管如果要访问该类型的static成员,则需要小心这一点)。

Given that it's private, you don't need to worry about whether or not subclasses would want to override it.鉴于它是私有的,您无需担心子类是否想要覆盖它。

You can always make it non-static later - I think the only side-effect of that would be to potentially change the serialization ID.您以后总是可以使它成为非静态的-我认为唯一的副作用是可能会更改序列化 ID。 (Binary serialization is a pain like that.) (二进制序列化就是这样的痛苦。)

Make it non-static if it needs access to non-static member variables, and make it static if it doesn't.如果需要访问非静态成员变量,则将其设为非静态,如果不需要,则将其设为 static。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM