guard clause

A check at the top of a function that handles an awkward or invalid case and returns or throws immediately, so the main logic stays unindented.

In more detail

Handling special cases first leaves the normal path at the left margin and makes the function easy to read. Each guard is a branch in its own right and deserves a test.

Examples

if (sku is null || sku.Length == 0) return "unknown";
if returned > paid:
    raise ValueError("cannot refund more than was paid")

Related terms

Taught in

References