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.

Prototype based object models

The Mozilla Developer Center has a great guide for Javascript. This guide provides one of the best explanations I’ve read on the Javascript object model and on prototype based object models in general.

Although I have only programed with languages that provide class based object models I believe that that prototype based object models are very easy to understand if you know the primitives of object oriented programming.

Prototype based object models are an interesting idea that suits very well with dynamic languages like Javascript. The only thing that I don’t really like is the syntax. For example creating a new “class” that inherits from an Employee “class” looks like this in Javascript:

function Manager () {
  this.reports = [];
Manager.prototype = new Employee;

And in Java:

public class Manager extends Employee {
  public Employee[] reports;
  public Manager () {
    this.reports = new Employee[0];

I prefer the Java version because the whole definition is included in one syntactic unit (a class definition), instead two in Javascript (a function definition and an assignment).

If I am correct, Ruby (BTW I don’t know Ruby and Javascript) has a class based object model but also has most of the features of languages that are prototype based. For example in Ruby, you can add or modify, at runtime, methods of classes and instances.