简体   繁体   中英

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).

If helper functionalities are small enough (and not needed by any other class) it makes sense to write a helper method in this class.

Now: assuming you'll need no access to any member variables, would it be better do make this method private or private static

the following example: just implements a method that checks if a string is not null and contains 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. 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. 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).

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. (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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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