Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 397
leifg Avatar asked Dec 09 '22 06:12

leifg


1 Answers

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

like image 54
Jon Skeet Avatar answered Jan 03 '23 08:01

Jon Skeet