Skip to content
Katabench
Try free

Flatten the Null Checks

Easy About 10 min Free, no account needed

An address printer hiding at the bottom of four nested ifs.

The brief

ShippingLabel(name, street, city, zip) returns the three-line label

Text
<name>
<street>
<city> <zip>

when every field is present (non-null, non-empty), and "incomplete address" otherwise.

The starter buries the happy path under four nested ifs. Refactor without changing behavior until every gate passes: guard clauses keep the nesting at zero.

Starter code

C#
using System;

public class Solution
{
    // Shipping label - the arrow anti-pattern in its natural habitat.
    public string ShippingLabel(string name, string street, string city, string zip)
    {
        if (name != null && name.Length > 0)
        {
            if (street != null && street.Length > 0)
            {
                if (city != null && city.Length > 0)
                {
                    if (zip != null && zip.Length > 0)
                    {
                        return name + "\n" + street + "\n" + city + " " + zip;
                    }
                    else
                    {
                        return "incomplete address";
                    }
                }
                else
                {
                    return "incomplete address";
                }
            }
            else
            {
                return "incomplete address";
            }
        }
        else
        {
            return "incomplete address";
        }
    }
}

How it is graded

Behavioral tests have to stay green while the grader measures complexity, nesting, method length, and duplication from your source.

C# refactoring exercises →

Related guides

What it practices

Guard clauses
Flatten nesting with early returns so the happy path reads top to bottom.

Related katas