Tell, Don’t Ask” principle — All You Need to Know
Today we are going to learn about Tell, Don’t Ask” principle with example.
Have you ever heard of the “Tell, Don’t Ask” principle?
The general idea is that you should avoid asking an object a question about itself to make another decision about something you are going to do with that object. Instead, you should push that responsibility into that object, so you can just tell it what you need without asking questions first.
The “Tell, Don’t Ask” principle encourages instructing objects to perform tasks rather than querying them for information and making decisions externally.
For example, instead of asking a thermostat if it’s too cold and then deciding whether to turn on the heater, you would simply tell the thermostat to maintain a specific temperature, allowing the thermostat itself to make decisions about heating. This approach promotes encapsulation and cleaner, more modular code by keeping decision-making logic within the object.
Let’s see some example with Laravel collection. If you don’t know about Laravel it’s just a PHP framework. I hope you can relate with any other language you know.
Instead of asking a collection for information and then making decisions externally, you can tell the collection what you want it to do.
Here’s a simple example:
Asking (Not Ideal):
$users = User::all();
// Asking for information
if ($users->isEmpty()) {
// Take some action if there are no users
} else {
// Take some action if there are users
}
Telling (Preferred):
$users = User::all();
// Telling the collection what to do
$users->each(function ($user) {
// Perform actions on each user
});
In the second example, you’re telling the collection to iterate over each user, and the collection itself decides how to handle the iteration. This adheres to the “Tell, Don’t Ask” principle, as you’re not explicitly checking the collection for information and making decisions outside of it. Instead, you’re telling the collection what to do, allowing it to handle the internal logic.
Hope you enjoyed!
Bonus: You must love my most read article : How To Use Single Responsibility Principle in PHP/Laravel
And most GitHub star repo:
https://github.com/mohasinhossain/SOLID-Principles-in-PHP