Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: When to make methods static v. instance [closed]

Tags:

java

oop

static

Instance, not static


For this case I think the second choice is clearly better. If you think about it, any method could be implemented as static if you are willing to pass the object to it, this only seems to be a special case because the other parameter is also an instance.

Therefore, our search for symmetry and abstraction is slightly offended by having to choose between the two instance objects for the dot operator. But if you look at .method as . then operator, it isn't really a problem.

Plus, the only way to do functional-style chaining is with an attribute, i.e., instance method. You probably want thing.up.down.parent.next.distance(x) to work.


When you make a method static, it means that the method can be called without an instance of the class. It also means that the method cannot access instance variables unless it is passed a reference to an object.

Sometimes, it makes sense to make a method static, because the method is associated with the class, but not a particular instance of the class. For example, all the parseX methods, such as Integer.parseInt(String s). This converts a String to an int, but does not have anything to do with a particular instance of an Integer object.

If, on the other hand, a method must return some data which is unique to a particular instance of an object, (like most getter and setter methods), then it can't be static.


IMO there is no absolute "better", but public int geneDistance(Gene other) is stylistically more similar to other methods in Java (e.g. Object.equals, Comparable.compareTo), so I'd go that way.


I prefer the second form, i.e. instance method for the following reasons:

  1. static methods make testing hard because they can't be replaced,
  2. static methods are more procedural oriented (and thus less object oriented).

IMO, static methods are ok for utility classes (like StringUtils) but I prefer to not abuse using them.