Tags: OO design
Inspiration: Nat Pryce
Object-oriented code is easier to understand and maintain if it is written in a "Tell, Don't Ask" style. Decisions are made by objects on information that they hold or receive as parameters, not on information that is held by other objects. That is, objects tell each other what to do by sending commands to one another, they don't ask each other for information and then make decisions upon the results of those queries.
The end result of this style is that it is easy to swap one object for another that can perform the same commands.
The extreme opposite is "train-wreck" code that contains lots of statements like "neighbour.getPart().getSubpart().getAttribute()". In this kind of code, the implementation of an object is coupled to the
structure of its neighbour, and so it is difficult to replace its neighbour with one that is implemented differently.
Sometimes you *do* need to ask an object about itself, for example when using Value Objects (which are immutable), Collections, and, although this is a slighty different case, Factories.
The main lesson is to be suspicious of queries and limit their use as much as possible.
Last published: Wednesday 24th March 2010
<<Previous Next>>