DEV Community

Cover image for The “Tell, don’t ask” principle
le0nidas
le0nidas

Posted on • Originally published at le0nidas.gr on

The “Tell, don’t ask” principle

This is one of my favorite principles because it is easy to spot when violated and because it helps in having proper API surfaces when applied.

Tell, don’t ask

In essence this principle proposes that instead of asking from an instance for its values in order to decide how the same instance will execute something, just tell the instance to execute it. It knows its own state, it can make its own decisions!

Asking

By asking we actually refer to accessing many of a class’s properties. For example:

in the code above we ask the task to provide the values of three of its properties in order to decide if we are going to close it or not.

In the process we (a) might had to expose those properties just for this code (creation date and subscribers could be private) and (b) inevitably leaked business logic that involves a task (when a task is eligible for closing).

Telling

Lets change the code in order to tell the task to close itself if possible:

There are two things that we gain from this change:

  1. we moved the “closing” logic in the Task itself which allows us to contain future logic alterations in just one place.
  2. the class’s API exposes only the necessary helping us to avoid accidental couplings.

Top comments (0)