Tell, Don't ask!
Tushar Goel
Lead Member Of Technical Staff @ Salesforce | Staff Software Engineer, Technical Lead
Few days back I was having a discussion with one of my friends and we were discussing how to reduce coupling between objects to improve the design.
In that we have discussed this principle and how does it help to improve the design. So I thought to share with you all as well hence in this article I will mention what it is and how it helps to reduce coupling.
Consider a simple example of Fish. Consider you will feed the fish only if they are hungry.
Following is an example of how we design in general:
class Fish {
?????????private boolean isHungry;
?????????public boolean isHungry() {
??????????????return isHungry;
}
public void eat() {
???????????// some work
}
}
class Feed {
???private Fish fish;
???public void feed() {
??????if (fish.isHungry()) {
fish.eat();
??????}
???}
}
What is the problem you can see here? Dependency on the internal state of other objects. Here we are first fetching the state of an object i.e. fish and then doing some action on it. So these 2 classes are tightly coupled. You can’t make any changes in Fish class without changing in Feed class.
So now, What if I can say, eat it if you hungry? What I meant is instead of asking it, tell it that eat it if you’re hungry? So that’s Tell don‘t ask.
So, the following are the changes:
class Fish {
??? private boolean isHungry;
public void eatIfHungry() {
???????????if (isHungry) {
?????????????????//some work
}
}
?}
class Feed {
???private Fish fish;
???public void feed() {
???????????fish.eatIfHungry();
???}
}
Do you see what I am pointing to? Instead of tightly depending upon the state, you are just telling it to do the work. So by doing this, you are hiding the internal structure of fish from the caller. Also, we can independently make changes in Fish class without making any impact on the caller.
So as we see this well help us to make design less couple. And as a developer, we know cohesion is good and coupling is bad.
References:
https://martinfowler.com/bliki/TellDontAsk.html