1.5.13 Debugging Nested and Conditional Returns

Overview

When a method has several conditions, a returned value may come from different lines in different runs. Break at the beginning of the method and at each return. Before stepping, write down the current field and parameter values so you can predict the route.

public bool CanUseBabyArea()
{
    if (this.Baby == null)
    {
        return false;
    }

    if (this.Sex == "Female")
    {
        return true;
    }

    return false;
}

This teaching example first rejects an animal without a Baby. If one exists, the second test checks Sex. Only an animal with a Baby and Sex == "Female" returns true. The second condition is never reached when the first return runs.

Step Through Each Route
Use three test states: Baby null; Baby present with Sex Female; and Baby present with another Sex value. In each run, observe the highlighted line move to a different return. After stepping out, check that the caller receives the predicted Boolean. T
Step Through Each Route
  • New
  • Changed
  • Removed

Use three test states: Baby null; Baby present with Sex Female; and Baby present with another Sex value. In each run, observe the highlighted line move to a different return. After stepping out, check that the caller receives the predicted Boolean. The same technique works for conditional totals in Date Night.

Trace the Outcome

If a return seems wrong, inspect the fields on this at the moment the method executes. A breakpoint in the caller alone will show the final result but will not reveal which condition selected it.

When the debugger pauses on a return statement, use Step Out to see the value arrive at the call site. Run each test state separately so the previous object state does not carry into the next test. If a field changes between calls, record the new value; a correct prediction for the first call may no longer apply to the second.