A simple example of “Tell, don’t Ask”

The “Tell, don’t Ask” object oriented principle says:

… you should endeavor to tell objects what you want them to do; do not ask them questions about their state, make a decision, and then tell them what to do.

Below I have a simple example from the Google Web Toolkit APIs that demonstrates how a small change in the API of a class to obey this principle can make the code more clean and remove code repetition.

In the first version (1.0.20 if I am correct) of the GWT in order to remove a Widget from its parent you had to write the following code:

Ask version

Widget w = ...;
if (w.getParent() != null) {
  Panel parent = w.getParent();

In the above code we ask the Widget object for its parent Panel (internal state) check that the parent is not null (make a decision based on the inner state of another object) and remove the widget from the its parent panel.

In the version 1.1.10 of the Google Web Toolkit the Widget class was refactored and a new removeFromParent() method was introduced. With this refactoring we can now write:

Tell version

Widget w = ...;

In this version of the code we don’t care if the Widget object has a parent or not. We simply tell to the Widget object to remove itself from its parent and the Widget object knows how to deal with all the variations of its internal state. The code now in much simpler and the repetition to check if the parent is null is gone.