Este post también está disponible en español
Tell dont ask is a principle of object-oriented programming that helps us remember that this paradigm is about creating objects with logic that operate on their data. To clarify, instead of asking an object for data and acting on that data, we should tell the object what to do because it knows its data.
Let’s see an example with code to better understand this idea.
Let’s imagine that we are programming a system that allows to manage tasks. These tasks can be finished when they are already finished, but you cannot finish a task that is already finished, this would cause an error. If we write this code with the style “ask” it would look like this:
class Task {
private id: number;
private name: string;
status = "pending";
constructor(id: number, name: string) {
this.id = id;
this.name = name;
}
}
let task = Task(1, "my first task");
if (task.status == "finished") throw new Error('Task is already finished!!!');
task.status = "finished";
In the previous code we can see how we ask data to task and we act with the information that it gives us. On the other hand, oriented to “tell dont ask” it would look like this:
class Task {
private id: number;
private name: string;
status = "pending";
constructor(id: number, name: string) {
this.id = id;
this.name = name;
}
finish() {
if (this.status == "finished") throw new Error('Task is already finished!!!');
this.status = "finished";
}
}
let task = Task(1, "my first task");
task.finish();
In this way we are encapsulating the data and the logic to the class that has the knowledge to do this operation. This is more familiar to the object oriented paradigm where we send “messages” to the objects to perform some operation with the data they know instead of asking for that data and performing some logic based on that, the “ask” style code looks more procedural.