Using private static methods

Andrey Vityuk picture Andrey Vityuk · Mar 26, 2009 · Viewed 58.3k times · Source

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.

Answer

eljenso picture eljenso · Mar 26, 2009

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.