I was just reading https://stackoverflow.com/questions/155609/what-is-the-difference-between-a-method-and-a-function and all of a sudden, the thing came to my mind was the static methods.
As static methods are no way associated with an object how can it be called as static methods (almost all developers do)? Is my understanding about the methods/functions is correct?
Best Answer
(Using Java terminology): Static methods can be associated with static members (members of the
class
object). If the methods don't access static members (nor IO resources or anything else that could change state), of if those members arefinal
primitives or immutable objects (essentially constants), then such static methods could be called functions, but in general, because they potentially could access theclass
object's members, they're usually called static methods.In order to count as a function, a method must be independent of any state; it must not cause any side effects nor be affected by any side effects. When called with specific parameters, it must always return the same result. Otherwise it's not a pure function.
That is, the following
area
is a function:while the following
getCallCount
is not a function:In general, mutable (non-
final
) static members should be used with caution - someone would say that they should not be used at all - because they make a global state to the program, which likely turns out to be a bad design choice in the long run. There are exceptions, but be careful...You don't even need static members to make static non-functions:
System.nanoTime()
is definitely not a pure function (because it returns different value on successive calls), even though it only accesses the computer's clock, not any static members.Confusingly enough, you could also make non-static pure functions:
Now, although not
static
any more,area
is still a pure function: it doesn't touch anything that could change. The fact that you would have to create an instance ofMyClass
to accessarea
doesn't reduce its "functionness". Indeed, one could argue that this kind of pure functions should always be made static.