Objects exposing behavior, not state

Controlling complexity of your codebase by limiting what state your objects expose

The more objects that can see and change states on other objects, the more complex your system. Objects returning a boolean mean that someone calling that method will use an if branch, returning an integer would mean someone using if/else or switch/case. Returning objects would mean introspeting that returned object to invoke something else on it. This increases coupling between classes, makes code hard to read and test.

My class has 3 friends, I talk to my friends’ friends. My friends are difficult to mock, therefore mocking sucks…

… well, yeah!

Testing procedural code is hard. Testing such code generally involves setting up “data” and asserting on state of objects. Tell Don’t Ask code on the other hand is easier to test since you’re not testing state. Also notice how DI makes things simpler to test.

void testOwnerCanFeedDog(){
    Dog dog = new Dog();
    // have to create a mouth since owner calls dog.getMouth() to feed it
    Mouth mouth = new Mouth();
    dog.setMouth(mouth);
    PetOwner owner = new PetOwner();
    owner.setDog(dog);
    owner.feedDog(food);

    // verify that the dog gets the food (well the mouth, actually)
    assertEquals(food, mouth.getFood());
}
void testOwnerCanFeedDog(){
    Dog dog = mock(Dog.class);
    PetOwner owner = new PetOwner(dog);
    owner.feed(food);

    // verify that the dog gets the food
    verify(dog).feed(food);
}

Without Dependency Injection, testing is quite difficult; without Tell Don’t Ask, testing is almost always impossible. Put together, things are separated, testing is simplified.