Tell, don't ask

From CSSEMediaWiki
(Difference between revisions)
Jump to: navigation, search
m
m
Line 11: Line 11:
 
  // Human's method to breathe
 
  // Human's method to breathe
 
  public void breathe() {
 
  public void breathe() {
     if(getLung() != null) {
+
     if(getLung().getOxygenAmount() < 0) {
      if(getLung().getOxygenAmount() < 0) {
+
 
           getLung().breatheSomeAir();
 
           getLung().breatheSomeAir();
      }
 
 
     }
 
     }
 
  }  
 
  }  
Line 30: Line 28:
 
  // Human's method of breathe
 
  // Human's method of breathe
 
  public void breathe() {
 
  public void breathe() {
     if(getLung() != null) {
+
     getLung().breatheSomeAir();
      getLung().breatheSomeAir();
+
    }
+
 
  }
 
  }
  

Revision as of 03:04, 20 August 2008

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.

Contents

Example

TellDontAsk.jpg

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() {
   if(getLung().getOxygenAmount() < 0) {
         getLung().breatheSomeAir();
   }
} 
// 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() {
   getLung().breatheSomeAir();
}
// 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 whether about the oxygenAmount at all. Lung makes a decision based on its internal attribute.

See also

Personal tools