A Guard Clause (one of the SmalltalkBestPracticePatterns, and equally applicable in a whole bunch of languages) is a chunk of code at the top of a function (or block) that serves a similar purpose to a Precondition.
It typically does one (or any or all) of the following:
- checks the passed-in parameters, and returns with an error if they're not suitable.
- checks the state of the object, and bails out if the function call is inappropriate.
- checks for trivial cases, and gets rid of them quickly.
function getInsuranceDeductible(insurance) {
if (insurance.covered) {
if (insurance.majorRepair) {
return 500
} else if (insurance.mediumRepair) {
return 300
} else {
return 100
}
} else {
return 0
}
}
function getInsuranceDeductibleBetter(insurance) {
if (!insurance.covered) return 0 // Guard clause
if (insurance.majorRepair) return 500
if (insurance.mediumRepair) return 300
return 100
}
For example:
draw() {
if (! isVisible()) return;
...
}
// without Guard Clause
function getPayAmount() {
let result;
if (isDead)
result = deadAmount();
else {
if (isSeparated)
result = separatedAmount();
else {
if (isRetired)
result = retiredAmount();
else
result = normalPayAmount();
}
}
return result;
}
// with Guard Clause
function getPayAmount() {
if (isDead) return deadAmount();
if (isSeparated) return separatedAmount();
if (isRetired) return retiredAmount();
return normalPayAmount();
}