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:
IMO, static methods are ok for utility classes (like StringUtils) but I prefer to not abuse using them.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With