![]() ![]() And we programmers never do unneeded things just because they are cool, right? Yes, it is micro-optimization, and probably unneeded. The JVM also can optimize static methods a lot (I think I've once read James Gosling declaring that you don't need custom instructions in the JVM, since static methods will be just as fast, but couldn't find the source - thus it could be completely false). SLIPSTACK METHOD CODEPerformance: if you want some code to be run, and don't want to instantiate an extra object to do so, shove it into a static method. There are some valid reasons to use static methods: This situation accounts for a fairly small fraction of all static methods, though. ![]() E.g.: Car theMoreEfficientOf(Car c1, Car c2)Īlthough 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. (By the way, the converse isn't always true: you might sometimes have a method which involves two Car objects, and still want it to be static. can't be static since it's inconceivable to call the method before any Car has been constructed. ![]() But this method (which sets the efficiency of one particular Car): void setMileage(double mpg) which would be static, because one might want to know what 35mpg converts to, even if nobody has ever built a Car. So in a class Car you might have a method: double convertMpgToKpl(double mpg) One rule-of-thumb: ask yourself "Does it make sense to call this method, even if no object has been constructed yet?" If so, it should definitely be static. ![]()
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |