There are some private methods in a class, and they don’t depend on any instance variables. They accept some arguments, and return a value, no side effects.
For example:
class User { private String firstName; private String lastName; public String getFullName() { return capWord(firstName) + " " + capWord(lastName); } private String capWord(String word) { return word.substring(0,1).toUpperCase() + word.substring(1); } }
You see there is a capWord
method in this class, which is private
but not static
. It’s safe to mark it as static
, but is there good enough reason to do this?
I have 2 reasons:
- when I see a method is
static
, I know it won’t read/write instance variables, which makes the code more readable - better performance
But I don’t know if they are enough to convince other members in team to change their private
methods to static
as more as possible.
Advertisement
Answer
You put forward two reasons for declaring such a method as static
.
Your first reason is valid, more or less. (It is actually saying more than what you said. A static
method can’t explicitly or implicitly call instance methods either! But it could have side-effects on objects that are passed as arguments, that are accessible via other static methods, and so on.).
Anyway …
It can improve readability if you declare a method as
static
to declare that it is not dependent on the state of a target object. However, for a typical small private “helper” method like that, it is pretty obvious that the method doesn’t depend on instance variables.The flip-side is that when you declare the method as
static
, you are constrained by that. For aprivate
method, that constraint is localized to the current class … and easy to modify. But for a non-private method, the constraint may affect other classes and cause problems.
Your second reason is debatable. If the method in question is small, then it is likely to be inlined by the JIT compiler, and that will negate any potential performance benefit. And even if there is a performance benefit, it is likely to be one or two instructions in the calling sequence, which is probably negligible compared to the application’s overall performance.
In summary, I think the “case” for declaring private methods like that to be static
is weak, and possibly incorrect. It is not something you should pester your colleagues about … IMO … unless you can present convincing evidence that it actually does affect performance AND that the performance improvement is significant to the overall application performance.