Where he blogs about his eclipse musings
Tell, Don’t Ask – Part 1
I spend more time reading code than writing it. I therefore like code that is readable. Rarely do I like to read code that is verbose and does too much orchestration in order to do something that is orthognal to what I’m looking for.
Code is easier to read and maintain when objects are written in a Tell Don’t Ask.
“Tell, Don’t Ask” is a style of programming where anObject tells anotherObject to doSomething(), rather than asking anotherObject to getSomeValue() and then makeADecision().
Code that does violates this this is more procedural than it is object oriented. In the procedural world code is written to fetch some data (or state) and then make a decision or perform some action. Procedural programming “pulls data” into the logic to get things done.
In object oriented programming, we do the opposite — have objects do something for you instead of you doing it yourself. Don’t overdo this too much, someone still has to do the real work though
Identifying places where you may tell instead of ask:
class PetOwner{
void feedDog(Food food){
if(getDog().isHungry()){
dog.getMouth().putFood(food);
}
}
}
This can instead be written as:
class PetOwner{
void feedDog(Food food){
dog.feed(food);
}
}
class Dog{
void feed(Food food){
if (iAmHungry()){
// consume food
}
}
}
Notice how the PetOwner does not know (or care to know) about the fact that the dog has a mouth.
September 4, 2009 - 1:23 pm
“Rarely do I like to read code that is verbose and does too much orchestration in order to do something that is orthognal to what I’m looking for”
Do you not see the irony in this statement.
September 4, 2009 - 2:29 pm
Nice example, it also describes improving an abstraction.
Adding the feed method to Dog is good because it conceals implementation details. Dog is no longer exposing the fact that it has a mouth, so there is no way for clients to depend on it.
Dog is now refactorable to Pet, too. And PetOwner can get a worm farm…
September 5, 2009 - 5:21 pm
Hi ketan,
Nice example,
I had a similar example of a dog wagging its tail.you don’t wag the dogs tail, you pat the dog or (as in this case) show it some food and it wags its own tail.
Jim
September 9, 2009 - 9:03 pm
I think it is important for the owner to know if the dog is hungry before he attempts to feed the dog. I’m not interested in forcing kibbles on a dog that isn’t hungry.
In this situation, I think some message or event would work out nicely. The dog could simply have a “IsHungry” event that the owner subscribes to. Then the owner knows exactly when to feed the dog.
I know that is how it works in my house