Tell Don’t Ask

Mohak Puri
Sep 4, 2018 · 1 min read

The Tell, Don’t Ask (TDA) principle suggests that it is better to issue an object a command to perform some operation or logic, rather than to query its state and then take some action as a result.

Let us discuss an example that I found (a simple google search). In the first case we are querying the state of the system and performing some action on it depending on the result.
In the second case rather than taking action on your own (asking) we are telling the monitor do something for us. This way we also preserve the encapsulation of the monitor.

That is wall the principle TDA is all about. Don’t ask a class for it’s state and then perform some action on that state instead tell the class what you want it to do.

// before 
def check_for_overheating(system_monitor)
if monitor.temperature > 100
system_monitor.sound_alarms
end
end
// after
monitor.check_for_overheating
class Monitor
def check_for_overheating
if temperature > 100
sound_alarms
end
end
end

In general, it’s ok to query an object for its state, provided the information isn’t being used to make a decision related to the object

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade