In code, that might look like this:
Campbell Ritchie wrote:Disagree. Only make something "static" when you have a good reason to. Always try non-static first.
Ernest Friedman-Hill wrote:Hi John,
Not needing access to static data is one criterion for allowing a method to be static. I'd add three more requirements even given thids first criterion is met.
2) Methods that might need to be replaced or stubbed out during testing. If a class has a method called "queryDatabase()", during testing you might want to write a subclass that overrides queryDatabase() to just return some canned data. If the method is static, you can't do that. If you're new to programming, you might not appreciate this last point, but it's very important.
So actually, that leaves only a few kinds of methods that really should be static. The methods in java.lang.Math that return the square root, absolute value, etc, are great examples. They're all concentrated in one class, and you'd never want to change their behavior. The default should always be instance methods; static methods are a fairly rare exception.
uj nossnahoj wrote:
A good rule of thumb is that you make the method non-static as a first approximation. You'll quickly discover whether this was the wrong choice because then you cannot use the method the way you intended. Then you change to static.