Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using private static methods [duplicate]

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.

like image 946
Andrey Vityuk Avatar asked Mar 26 '09 12:03

Andrey Vityuk


People also ask

Are private static methods bad?

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.

What is the point of private static methods?

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.

How do you call a private static method from another class?

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.

Can static methods be overloaded?

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.


1 Answers

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.

like image 165
eljenso Avatar answered Oct 05 '22 06:10

eljenso