javaoopcoding-stylestatic-methods

Using private static methods


What do you think about using private static methods?

Personally, I prefer using a static private method to a non-static one 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 a style perspective, not performance.


Solution

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