Tell, don't ask
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.
Example
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 of breathe public void breathe() { if(getLung().getOxygenAmount() < 0) { getLung().breatheSomeAir(); } }
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 "Tell, don't ask" principle suggests that the Human object should tell Lung what to do, and let Lung deals with the actual oxygenAmount to decide whether the Human should breathe or not.
// 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 tell the Lung to breatheSomeAir(), and does not care whether about the oxygenAmount at all. Lung makes a decision based on its internal attribute.