Why would there be an advantage to use a static method and pass the reference to an object as a parameter rather than calling the method on an object?
To clarify what I mean, consider the following class:
public class SomeClass {
private double someValue;
public SomeClass() {
// Some constructor in which someValue is set
}
public void incrementValue() {
someValue++;
}
}
Compared to this alternative implementation with a static method:
public class SomeClass {
private double someValue;
public SomeClass() {
// Some constructor in which someValue is set
}
public static void incrementValue(SomeClass obj) {
obj.someValue++;
}
}
My question is not restricted to this class alone; any point where you'd pass an object instead of calling it on a method is what I'm interested in. Is this ever advantageous? If so, why?
Best Answer
A trivial example: when the instance passed can legitimately be null and you want to incorporate the (non-trivial) handling of this into the method.