This post originated from an RSS feed registered with Java Buzz
by Michael Cote.
Original Post: Demeter's Law Remix
Feed Title: Cote's Weblog: Coding, Austin, etc.
Feed URL: https://cote.io/feed/
Feed Description: Using Java to get to the ideal state.
What that means is that the more objects you talk to, the more you
run the risk of getting broken when one of them changes. So not only
do you want to say as little as possible, you don't want to talk to
more objects than you need to either. In fact, according to the Law
of Demeter for Methods, any method of an object should only call
methods belonging to:
Yet, I maintain that the first piece of code is
actually quite dangerous. If you ever go multithreaded
and don't explicitly protect your two calls with a
synchronization (which will degrade overall
efficiency), then you might be acting at on different
variables at different times depending on how the
iterator is coded and who has a handle on it.
To which my first response is, in the immortal re-phrasing by Kinman,
"TU ES CORRECTO, SENIOR! SI!" Using an
Iterator in this fashion is indeed a very bad
idea. But, what if the object wasn't going to suddenly change state
because some schmuck-thread called next()?
Keep Returned Values
The rule of thumb I tend to follow is
that if I'm going to be using a return value from an object more than
once, I put it into a local variable, e.g.,
snapshot. This is more a code-readability issue than
anything else: it looks less cluttered. On the other hand, one could
successfully argue that it does seem to clutter up the code
more; what's clutter and what's not isn't often black and white. (If you're one of these people, you're probably also nuts for
code like,
new DoSomething(new Date(), new String [] {"param1", "param2").execute();
That shit drives me crazy, but some folks like it.)
Query Once
On a more technical, and paranoid-design
school, note one doesn't always know what a seemingly simple
getSnapShot() type method will do: it might be more than
an innocent JavaBean property, e.g., it might call across the network,
call into the DB, re-calculate the value, etc.
More importantly, you can't predict what that method will do in the
future: getSnapShot() might be a simple JavaBean
property now, but someone might change it, making it more complex and
time intensive. Obviously, when making that kind of change, you'd want
to go through and check all the code that uses your new, slower
version of the method...but there's always a wide gap between "want"
and actually doing: though good tools make finding calling code brain-dead
easy, programmer laziness often saps even the ability to right-click.
Debugging
As a last item, assigning the return of
getSnapShot() to a local variable makes debugging
slightly easier: you can just inspect the local variable rather having
to get your debugger to execute getSnapShot() and show
the result. (The same goes for the parenthetical referenceless new
class instance example above.)