I've read about static vs. instance methods here, but I don't see any that answer this particular question (green as it may be).
When you have a class with some properties, and a method in that class that needs to use those properties, is it better to do it with a static or an instance method?
I.E.
class Foo
{
//properties
bar1;
bar2;
//method
sumbar1andbar2()
{
return bar1 + bar2;
}
}
The sumbar1andbar2 method needs both the properties of the Foo class to be present. It seems a bit goofy to make a static method and call it this way, since I'm manually passing the members of the class into the class's method:
Foo foo1 = new Foo();
foo1.bar1 = x;
foo1.bar2 = y;
sumbar1andbar2(foo1.bar1, foo1.bar2);
But although the instance method below seems much cleaner, I'm not aware of a clean and easy way to ensure that both bar1 and bar2 are not null, which would cause an exception:
Foo foo1 = new Foo();
foo1.bar1 = x;
foo1.bar2 = y;
sumbar1andbar2();
However, the instance method seems even better if the method modifies another property of the class, like bar3.
First, there is a nice and easy way to ensure that your properties are not null: it is called encapsulation. Make sure the properties are set in the constructor, and do validation in their setter if you choose to expose one. This way the properties will be non-null after the object is constructed (otherwise, constructor would throw an exception), and the property setters would leave property values in a consistent state (otherwise, setters would throw an exception).
Now to the actual question: if one or both values could potentially be coming from other instances of
Foo
, make the calculating method static. Otherwise, make it an instance method.P.S. If your method returns a value, does not have parameters, and does not produce side effects, consider making it a calculated property instead of a method.