TDD: Tell, Don’t Ask

Test driven development follow this pattern: Setup – Execute – Verify the new state. Asking the system under test for its new state has traditionally been done to check the new state. This can create problems with the Law of Demeter. The system under test knows unnecessary much about the objects it is collaborating with.

This may not seem like a big deal, but when you try to break things apart and replace an object you may end up with refactoring a lot more than you actually wanted. It is like pulling up a tree with the roots. You will damage the ground a lot and have tons of soil among the roots afterwards.

Another approach would be to tell the system under test what to do and verify that it has been told properly. This will reduce coupling between objects, not break encapsulation, allocate functionality in the proper place, name functionality better according to the problem domain and prevent classes from being feature envy. I will show some examples where I ask for the state and then compare them when I apply Tell – don’t ask and discuss the differences.

Video producer: JDD Conference