What do you think about using private static methods?
Personally, I prefer using a static private method to non-static as long as it does not require access to any instance fields.
But I heard that this practice violates OOP principles.
Edit: I am wondering from style prospective of view, not performance.
It is advisable to mark your private methods as static if they are not using any of the instance object for slightly better performance and readability. Infact the following warning in code analysis is shown if such methods are not marked as private.
Private static methods can for example operate on private static members of their class. This can be utilized to encapsulate and unify certain class specific operations.
You shouldn't access a private function/variable from outside of that class. If you need to access a private variable of a class, you can create an accompanying getter for that variable, and call the getter function on the class.
As per Java coding convention, static methods should be accessed by class name rather than an object. In short, a static method can be overloaded, but can not be overridden in Java.
A private static
method by itself does not violate OOP per se, but when you have a lot of these methods on a class that don't need (and cannot*) access instance fields, you are not programming in an OO way, because "object" implies state + operations on that state defined together. Why are you putting these methods on that class, if they don't need any state?
(*) = In principle, due to the class level visibility in Java, a static method on a class has access to instance fields of an object of that class, for example:
class Test { int field = 123; private static void accessInstance(Test test) { System.out.println(test.field); } }
You need to pass in the reference to an instance (this
pointer) yourself of course, but then you are essentially mimicking instance methods. Just mentioning this for completeness.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With