2.2. Tests Communicate Your Intent

In a perfect world, your code would stand on its own and communicate your intent without resorting to written documentation. Martin Fowler asserts in his book Refactoring that if you feel you need to add comments to your code to properly express your intent, then you need to refactor. It should be obvious to anyone who views your code what it was you intended it to do and how it is intended to be used. This might be a little idealistic and really represents more of a theoretical goal than an actual state of affairs. It is also harder to achieve in designs that are less strictly object oriented. In today's Service Oriented Architecture (SOA) or other message-passing-style architectures, the semantics of the code can be harder to determine solely by reading the code.

In cases where the design may be less intrinsically clear, tests can help to communicate your intent better than external written documentation or code comments. For example, take the following version of your calculator interface:

public enum Operator
{
    Add,
    Subtract,
    Multiply,
    Divide
}

public interface IRPNCalculator2
{
    void Push(int operand);
    void Push(Operator theOperator);
    int Result();
}

This interface may in many ways be easier to use than the versions previously discussed, but it might be harder to understand at first glance. The equivalent test might look like this:

[Test] public void AddADifferentWay() { IRPNCalculator2 calc = new Calculator2(); calc.Push(2); calc.Push(2); ...

Get Code Leader: Using People, Tools, and Processes to Build Successful Software now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.