Tell, don't ask

From CSSEMediaWiki
Revision as of 11:13, 29 September 2010 by Scott Parlane (Talk | contribs)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

Procedural code gets information then makes decisions. Object-oriented code tells objects to do things.Alec Sharp in Smalltalk by Example

In software engineering, the "Tell, don't ask" principle states that objects should tell each other what to do by issuing commands to one another, rather than asking each other for information and then make decisions based on the information obtained. As a consequence, an object only makes decisions based on its internal information. It does not care about or need to obtain external information before telling the other object what to do. This makes the implementation cleaner and simpler.

"It is okay to use accessors to get the state of an object, as long as you don't use the result to make decisions outside the object. Any decisions based entirely upon the state of one object should be made 'inside' the object itself."




To illustrate this principle, let us have a look at a simple example above: Human contains a Lung. And now, we want for a Human object to breathe.

The "Ask" version

Now, if we were to implement this in the ASK version, we will do as follows:

// Human's method to breathe
public void breathe() {
   Lung myLung = getLung();
   if(myLung.getOxygenAmount() < 0) {
// Lung's method to breathe
public void breatheSomeAir() {
   ... // do the necessary action to breathe

Notice how Human asks for Lung's oxygenAmount and based on the value obtained, decides whether to breathe or not.

The "Tell" version

Now, let us implement the exact same thing, but using the principle. The principle suggests that the Human object should tell Lung what to do, and let Lung deals with the actual calculation of looking into the amount of the Oxygen present in the Lung to decide whether the Human object should breathe or not. Thus, we will have as follows:

// Human's method of breathe
public void breathe() {
// Lung's method to breathe some air
public void breatheSomeAir() {
   if(getOxygenAmount() < 0) {
        .... // do the necessary action to breathe

In this case, Human's breathe() method tells the Lung to breatheSomeAir(), and does not care about the oxygenAmount at all. Lung makes a decision based on its internal attribute.

See also

Personal tools