In the English version I saw this question, but I did not find it in the Russian version. Often, some programmers use private static methods to show that this private method does not use any class variables and methods, others, on the contrary, oppose this approach because it does not use the OOP correctly (we are talking only about private class methods that do not use any class variables and others static methods).

That is, what is more correct for you to use so

  public class MyClass { private static void func1() { // со статик ... } } 

or so

  public class MyClass { private void func1() { // без статик ... } } 

?

I talked about methods that do not use (and cannot use) fields directly, for example, the boolean isValid(T str) method, which is called in other class methods for many different objects, and which are needed only for this class and carry them to Separate Utils class makes no sense.

As an example of such a method, it is hugeCapacity in ArrayList from Oracle JDK 8 :

 private static int hugeCapacity(int minCapacity) { if (minCapacity < 0) // overflow throw new OutOfMemoryError(); return (minCapacity > MAX_ARRAY_SIZE) ? Integer.MAX_VALUE : MAX_ARRAY_SIZE; } 

PS Any quotes and references to well-known Java authors will help to solve the problem (for example, I know that in ArrayList from Oracle JDK , where the authors are quite well-known Josh Bloch and Neal Gafter, private static methods are used). Maybe you know other evidence of this or that point of view?

That is the perfect answer, this is the answer with quotations for books / articles of well-known Java authors or those who were engaged in OOP theory or design.

  • in terms of correctness, both options are correct, in terms of performance - private static is the best hint to the compiler for optimization and inlineing - Artem Konovalov
  • речь только о приватных методах класса - is it just "only about private methods of the class" or "about private methods of the class that do not use any variables and methods of the class"? - Alexey Shimansky
  • Which use nothing and which without problems can be put static. The question is whether it is necessary. - Viacheslav Vedenin
  • Usually, if the first version comes across in the code, it means that the method is not in its place. - AseN
  • one
    Hmm, well, it's nonsense for the sake of optimization to make the method static. If static methods are faster, then these are questions to the compiler, it should look at whether the method depends on the members of the class and do the corresponding optimizations on their own - Andrey NOP

7 answers 7

Be guided by the meaning, and only them. The structure of your classes should not reflect the technical ability to do this or that (sometimes you can declare instance methods static), but relations between objects in the domain domain. This is indeed the basis of the entire PLO (and where else to follow the PLO, if not in Java?).

I can not quote from a smart book about this. But the idea of ​​making the signature of a method dependent not on its meaning , but on the details of its specific implementation seems to me a crude hack. Even if it is an internal, private method. If we write correctly in public methods intended for others, then why is it wrong to write in methods intended for ourselves?

Good reasons are needed to digress from the right design. ArrayList such reasons: it is used in millions of projects, and there are time-critical pieces among them, and winning a pair of bars plays a significant role. But for most classes that we write, the number of calls in our programs is not tens of thousands per second, and deviation from the correct design is hardly justified.


If a method relates to a specific object, then declare it to instance methods, regardless of whether it refers to non-static fields and whether or this . If the method is common to the entire class, and does not make sense in the context of a single instance, declare it static. If the method does not belong to a class at all, move it to an auxiliary class.


Example: a knight's weapon is a sword. Yes, all knights have the same weapon. However, the weapon-issuing method is obviously an instance method. Further, knights do not use daggers. Therefore, the knight's getter dagger returns null . This is also an instance method.

 class Knight : Warrior { private Weapon createMainWeapon() { return new Sword(); } private Dagger getDagger() { return null; } } 

Next, the number of knights. Accordingly, it does not make sense in the context of a single knight, which means it is a static method.

 class Knight : Warrior { static int numberOfKnights; public Knight() { numberOfKnights++; } public static int getNumber() { return numberOfKnights; } } 

Finally, the method that ascertains whether the ammunition is in order before the battle is not at all related to the knight’s field of activity. Let the squire do it!

 class Squire { Knight master; public prepareForBattle() { ... } } 
  • How about the KnightArmy class being responsible for the number of knights, and not the knight's static method? - AseN
  • 3
    @AseN: Yeah, or so. But I would avoid over-creating entities so that it doesn't work out . - VladD

First, for a start, it would be good to decide whether this method is necessary for this class? Let's say we have a car class and a method for converting kilometers to miles.

 public class Car { private static double convertToMiles(double km){ return km*0.621371192; } } 

Obviously, this method is generally not needed by the class and it would be good to put it into a separate final Utils similar class, as many places can be used.

Renaud Waldura in "The Final Word on Final" writes:

There is no need for a dynamic method, and it can be used instead. The compiler can direct a call to the method, bypassing the virtual procedure invocation procedure. Just-In-Time compiler or a similar optimization tool. (Remember, private / static methods are already final, therefore always considered for this optimization.)

I personally do static possible to show that the method does not depend on the state of the class and does not affect it in any way. In the IDE, such a method will be highlighted with an italic font, which makes it possible to understand its independence from the state of the class, without even looking inside the method.

  • Here the question is a little different. You have described the case when the method is not needed, but the author is interested, if this method is needed then how will you make it static or normal? - Victor
  • four
    @ Victor static . Just like if a variable is assigned once, I will make it final , etc. This is all from one opera. - Suvitruf
  • A separate problem is the Util-classes, which are in essence a “hack” of OO-ideas and a secretive return to the functional paradigm. What is usually bad, especially in large projects. - AseN
  • @AseN Math class? - Suvitruf
  • Math-class is a great example of the problem described above by one comment, where everything is piled up. - AseN

For a deeper understanding, I will add a historical context in general about static methods. Some question researchers generally consider all such methods to be evil in OOP.

When a topic is difficult to understand, then one of the best ways is to turn to history. Java derived from Smalltalk. This is known to all who have spent at least one day studying it. In the language of Smalltalk (since 1971), there were already static methods - though they go there under the name "class methods". Where did they come from? Smalltalk has another ancestor - Simula (since 1965). It turns out that in Simula there were such methods - only there they go under the name "free block". But in turn, who “dragged” these “free blocks” from the language of Simula? And the ancestor of the Simula is Algol. Because Simula was originally a superset of Algol 60. So, that's where your legs grow from:

a) Algol

 procedure Absmax(a) Size:(n, m) Result:(y) Subscripts:(i, k); value n, m; array a; integer n, m, i, k; real y; comment The absolute greatest element of the matrix a, of size n by m is transferred to y, and the subscripts of this element to i and k; begin integer p, q; y := 0; i := k := 1; for p := 1 step 1 until n do for q := 1 step 1 until m do if abs(a[p, q]) > y then begin y := abs(a[p, q]); i := p; k := q end end Absmax 

b) Simula

 Begin Class Glyph; Virtual: Procedure print Is Procedure print; Begin End; Glyph Class Char (c); Character c; Begin Procedure print; OutChar(c); End; Glyph Class Line (elements); Ref (Glyph) Array elements; Begin Procedure print; Begin Integer i; For i:= 1 Step 1 Until UpperBound (elements, 1) Do elements (i).print; OutImage; End; End; Ref (Glyph) rg; Ref (Glyph) Array rgs (1 : 4); ! Main program; rgs (1):- New Char ('A'); rgs (2):- New Char ('b'); rgs (3):- New Char ('b'); rgs (4):- New Char ('a'); rg:- New Line (rgs); rg.print; End; 

Thus, the PLO was initially a superstructure above the imperative one - therefore, it will not be possible to completely “cut out” static methods. In institutional economics, there is such an observation — the priority / importance of a rule is determined only by one — the cost of changing (or canceling) it. "Cancel" static methods will cost mankind so many person-years that they are probably with us forever. We can only reduce their use in our own code in order to more conveniently work with objects.

As for private static methods, we add privacy to the common drawbacks of static methods. Very rarely met such methods in the code. I do not use it myself, because I try to minimize static methods in the code altogether and consider myself to be supporters of the ideas of Egor Bugaenko.

  • one
    What is the lack of "privacy"? - rjhdby

Immediately mark IMHO: the method should not be static and in a post I try to describe this point of view.


Everyone creates their own code. Maybe this is relevant for optimization, but not for OOP. It turns out this is not a method, but a procedure.

Quote from an interview with David West:

"The class should not do anything"

Egor: But in Java classes are not just forms for objects. We put methods there ...

David: And in vain!

Egor: That's my question!

David: Well, as I tried to say in the book, the class should not do anything. Smalltalk has class methods, but don't use them. Their use is a return to the command mode of thinking. You take what should be the responsibility of objects, and for some reason you are trying to push it all into a class. And in the end, the class does a lot for the objects.

full interview


It all boils down to one question, why should this method belong to a class, not an object?


Now I thought that this quote is not in the subject of the question, but let it remain.

I do not quite understand the purpose of making the private method static. If only for optimization.

If you do not take into account the optimization, the method operates with fields of the object (they will simply be passed as parameters). And here you can remember the "clean code". The smaller the parameter method, the easier it is to read. So you can make it not static and use not the parameters, but the fields of the object.

If the private method takes no parameters and does not access the variables of the object, then I don’t quite understand what it will do.


Update: I talked about those methods that do not use (and cannot use) fields directly, for example the boolean isValid method (T str), which is called in other class methods for many different objects, and which are needed exclusively for this class and endure them in a separate Utils class makes no sense.

The object's validity can be determined by the object itself, and a “information expert” is needed here, and then the essence of the generic method goes to each class, i.e. instead of the static method of validity of any object, we ask the object itself whether it is valid.

  • Honestly, I completely understood how your answer answers the original question. What point of view do you hold in the end, do I understand correctly that static private methods are not needed? - Viacheslav Vedenin
  • @ViacheslavVedenin added, to be honest, I don’t quite imagine the problem, more precisely when it can be used. Cited a common quote, because stumbled upon an article yesterday and seemed appropriate, but not quite - Victor
  • The method may not operate with fields, and in any case, take parameters, for example, the boolean isValid (T str) method, which is called in other class methods for many different objects. Well, let's say it is exclusively for this class. - Viacheslav Vedenin
  • @ViacheslavVedenin if this method is used within the same class, then the whole difference will be in the indication of the method parameter. And here comes the quote "The class should not do anything," the object itself can say whether it is valid or not. - Victor
  • Updated the question, an example of such a hugeCapacity method in ArrayList from Oracle JDK 8. - Viacheslav Vedenin

Perhaps this is the most brief explanation of the use of static methods.

Static methods should be applied in two cases.

• When the method does not require access to the object's state data, since all the necessary parameters are set explicitly (for example, in the Math.pow () method).

• When a method needs access only to static fields of a class.

Horstmann, Kay S. Java. Library Professional, Volume 1. Basics. 10th ed. p.157

  • In my opinion, this is obvious. I do not see the point in such an explanation. - Drakonoved

The first duty I want to say is my opinion this is my experience !!! (I think that you know the essence of the usual and static method therefore I do not write the definition.)

  1. The statistical method is a functional approach. In object-oriented design, this affects the development, that is, maintenance is difficult, thinking changes to functionality, and so on (general response) .

  2. Well, from the point of view of memory, the usual or static method does not have a loss why: The memory ".NET / Java" uses the Flyweight technique (even this technique has a pattern but this is not the point). This technique saves RAM (I will not explain the technique in detail), and here the usual or static method does not affect anywhere (in terms of memory), because each class is allocated one object (this is a technical name) which methods are contained in this object each the instance only contains the usual Fields/Properties (mutable) and these instances refer to this object , and here are the brief points. (here implies technical influence).

I want to touch on one moment. The problem is that in any ordinary or static method you cannot load a large responsibility or a large amount of code (one of the important principles). I think that it is not necessary to look at this topic so critically.

I will not philosophically tell a fairy tale. Well divided into two parts (analyze) .

Well, I can recommend a philosophical book on these topics "Object Thinking David West" here explains in detail the pure object-oriented programming / thinking, architectural difference and such topics as static, conventional (methods, classes) and so on.

    No wrong. More precisely, it is wrong to make private class methods static. Technically, of course, this can be done, but there are cases where it is harmful and unnecessary.

    I will give an example: I often see, in the same Android, when a new super-duper API is announced, then when studying the sources, it turns out that they simply made the previously private method in the class public. That is, Google is actively using private non-static methods as a way to manage versions. The meaning is simple, there is a private method that is hidden inside the class and is actively used by normal public methods, thus the method passes a kind of run-in under real conditions. Then, after studying the bugtracks, the development team decides to bring the method out: the method signature is declared as public and is ready — the progs get a new API tool in their hands.

    I think this is a very good practice. And at least for the sake of this method of declaring a private method static would not be worth it.

    • Not quite understood, but what's the difference in this case? It is possible to change private static to public. And other methods can use both options. - Viacheslav Vedenin