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
- null-keyword — A special value meaning a reference points at nothing.
- exception — An error object a program raises to stop normal flow and report that something went wrong.
- branch coverage — A measurement of whether each decision in the code, such as an if statement, was taken both ways during the tests.
- error path — The route through code taken when something goes wrong, such as invalid input, a timeout or a failed dependency.
Taught in
- The C# Language: Types, Variables, and Flow Control — Modern .NET Core, C# & Enterprise Microservices
- Coverage: Diagnostic, Not Target — Automated Testing, TDD & Quality Engineering
- Introducing pytest — Automated Testing, TDD & Quality Engineering