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
<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
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.
Related guides
What it practices
- Guard clauses
- Flatten nesting with early returns so the happy path reads top to bottom.
Related katas
- Tame the Grade Calculator Easy Free Letter grades with bonuses, written as a wall of nested ifs.
- Flatten the Config Fallbacks Easy Pro Three levels of default-chasing, one nested if per level.
- Flatten the Cursor Decoder Easy Pro A cursor envelope is validated inside a deep branch pyramid. Extract canonical number parsing and flatten the protocol guards.
- Flatten the Date Window Easy Pro Is the date inside the campaign window? Nested month/day comparisons say maybe.