1.6.6 Making Decisions with Nested if Statements

Overview

The Zoo birthing-room assignment has two questions: is there already a Baby, and is the Animal female? These checks have different purposes. A nested if can express that the second question matters only when Baby creation has not already been ruled out.

if (this.Baby == null)
{
    if (this.Sex == "Female")
    {
        this.Baby = new Animal();
    }
}

If Baby is already non-null, no second check or replacement occurs. If Baby is null, the method checks Sex and creates a Baby only for the Female value. The complete Zoo method also initializes the new Baby’s other fields inside the same branch.

Reason About the Zoo State
This view starts with the question “Baby already exists?” so its Yes path preserves the object. The code above starts with Baby == null, so its Yes path proceeds to the inner check. Both representations describe the same behavior even though one cond
Reason About the Zoo State
  • New
  • Changed
  • Removed

This view starts with the question “Baby already exists?” so its Yes path preserves the object. The code above starts with Baby == null, so its Yes path proceeds to the inner check. Both representations describe the same behavior even though one condition is phrased in the opposite direction.

Trace the Outcome

For a Baby already present, a female animal without a Baby, and a male animal without a Baby, identify the path and the resulting Baby reference. Do not confuse a false Sex == "Female" result with a null Baby test.

An early-return version can check GetIsPregnant() first and exit, then test Sex. That changes the shape of the code but preserves the two requirements: do not replace an existing Baby, and create a new one only for a female Animal. When comparing implementations, trace the resulting object references rather than comparing only the spelling of conditions.