On Mar 11, 9:11 pm, Göran Andersson <g...@guffa.comwrote:
To add a bit to what has already been said:
Passing parameters instead of using global variables was a good practice
before object orientation, but that is no longer needed as the variables
are no longer global.
I agree with you generally speaking, but I disagree with this as a
hard-and-fast rule. All O-O did was make truly global variables almost
extinct, and moved the scope of "global" data into a class definition.
Some classes are quite complicated, and contain a lot of data. In such
cases, there _is_ value in creating private methods that are clearly
marked as not needing the entire state of the object in order to do
their work. This can be valuable because one can immediately see by
looking at the method that it needs only two or three pieces of the
object's state in order to function. It is no longer necessary to read
the method's code (and the code of everything it calls) in order to
know for sure what parts of the object's state it reads, and what
parts it alters.
In other words, it's the old problem of global variables in-the-small:
the class's fields become the "global variables" if you will.
However, the OP's original idea was extreme, IMHO. Once you end up
with more than a handful of items being passed to a private "helper"
method, or once you end up with "ref" or "out" parameters because the
method alters more than one field in the object's state, then IMHO
it's time to drop the parameters and just make the thing a
parameterless method that works directly on the object's state.
As well, in order that this have value, the class has to have a large
number of fields. If the thing has only five or six fields, then
making a private method static in order to demonstrate that it needs
only two of them is overkill.
Actually, if you are creating a method that doesn't use any members of
the class but only the parameters, you should make the method static, so
that it's obvious that it's independent.
Absolutely. You stole my thunder on this point. Yes, it is helpful to
make some methods "independent" of object state by passing what they
need as parameters. However, if you're going to do that then you
should always make the method static. Otherwise you're missing out on
a great opportunity to clearly "promise" to the reader that the method
neither reads nor writes any more of the object's state than the
parameters that you've provided. A private _instance_ method that has
everything passed to it is nothing more than a code bomb: someday
someone is going to "tweak" it to read or write some object state
directly (because it's easier than changing its parameter list), or
change it to call some other method that in turn reads the object's
state, and then the advantage of passing arguments--that it clearly
indicates what the method works on--is not only lost, but misleading.
If you're going to pass it everything it needs--and that's often
valuable--then it should be static.