Ian Taylor wrote:...Under which circumstances (broadly speaking) would you choose one over the other?
Broadly speaking, if the method defines a self-contained "function", then it's better to make it
static (and possibly even define it in a utility class); if it relies on any state of a particular object, then it should almost invariably be an instance method.
So, a logarithm function should probably be
static, since what it does doesn't rely on anything except its parameters; but a
currentSpeed() method for a Car is linked to a
specific Car, and therefore should be an instance method. The alternative of making it a
static method that
takes a Car as a parameter makes the method overly reliant on the way a Car produces that information, and so breaks encapsulation (Google it) and makes the method
tightly coupled - one of those "code smells" that you may have already heard about, and that we hoary old farts hate.
Is one fundamentally better? The first way (using static methods) always seems much easier to me, but it seems whenever I read java tutorials, it encourages using class instances more.
I'd say that, as a guideline, they're probably right. Instance methods are less "invasive" to a design, so you should generally prefer them to a static method if you have a choice. As with everything of course, there are exceptions; but I'd say that a good rule of thumb would go something like this:
Prefer instance methods to
static ones, and only write the latter if you feel confident that you can
justify it.
Whatever you do, don't write
static methods simply because you find them easier - it's sloppy thinking and, as you get more experienced, it won't always be the case.
HIH
Winston