Tuesday, December 31, 2013

I am wondering when to use static methods? Say If i have a class with a few getters and setters, a method or two, and i want those methods only to be invokable on an instance object of the class. Does this mean i should use a static method?
e.g
Obj x = new Obj();
x.someMethod
or
Obj.someMethod
(is this the static way?)
I'm rather confused!
share|improve this question
add comment

13 Answers

up vote175down voteaccepted
One rule-of-thumb: ask yourself "does it make sense to call this method, even if no Obj has been constructed yet?" If so, it should definitely be static.
So in a class Car you might have a method double convertMpgToKpl(double mpg) which would be static, because one might want to know what 35mpg converts to, even if nobody has ever built a Car. But void setMileage(double mpg) (which sets the efficiency of one particular Car) can't be static since it's inconceivable to call the method before any Car has been constructed.
(Btw, the converse isn't always true: you might sometimes have a method which involves two Carobjects, and still want it to be static. E.g. Car theMoreEfficientOf( Car c1, Car c2 ). Although this could be converted to a non-static version, some would argue that since there isn't a "privileged" choice of which Car is more important, you shouldn't force a caller to choose one Car as the object you'll invoke the method on. This situation accounts for a fairly small fraction of all static methods, though.)
share|improve this answer
37 
A few good examples here. I would add, however, that "static" is often valuable when you know something is not going to change across instances. If this is the case, I would really consider the "Single Responsability Principle", which implies a class should have one responsability and thus only one reason to change. I feel one should consider moving the "ConvertMpgToKpl(double mpg)" function, and similar methods, to their own class. The purpose of a car object is to allow instantiation of cars, not provide a comparison between them. Those should be external to the class. –  Zack Jannsen Aug 13 '12 at 11:04 
add comment
Define static methods in the following scenarios only:
  1. If you are writing utility classes and they are not supposed to be changed.
  2. If the method is not using any instance variable.
  3. If any operation is not dependent on instance creation.
  4. If there is some code that can easily be shared by all the instance methods, extract that code into a static method.
  5. If you are sure that the definition of the method will never be changed or overridden. As static methods can not be overridden.
share|improve this answer
10 
+1 for clean, direct, and to the point! –  Zack Jannsen Aug 13 '12 at 11:12
 
good points, but they are requirements if you want to make a method static, not reasons to make one. – tetsuo Dec 11 '13 at 14:17
add comment

No comments: