
This short refactoring tutorial explains how to write guard clauses for your if statements instead of nesting conditional if … else logic. It is one of the quickest ways to get clean, readable code. The example is written in JavaScript, but the same style applies to any language, PHP, Java, and the rest.

What is a guard clause?
The guard clause pattern is simply a way of running early checks inside a method, in a constructor, for instance. When a method (or an object instance) needs certain values to work correctly, and the application should never call that code with invalid input, the guard clause throws an exception as soon as a value fails one of the successive conditions. Among other things, the technique avoids stacking nested if … else blocks along the execution path of a method.
A JavaScript example of the guard clause technique
Say you have to write a method that formats a date depending on its value: it may be a timestamp, a Date object or a string, and anything else is an error. The tempting approach is a chain of nested if / else if / else statements.
Without guard clauses
function getDate(date) {
let result;
if (!isEmpty(date)) {
if (isTimestamp(date)) {
result = formatWithTimestamp(date);
else if (isDateObject(date))
result = formatWithObject(date);
else if (isString(date))
result = formatWithString(date);
else
throw new DateFormatException(date);
}
return result;
}
return emptyDateError();
}
With guard clauses
function formatDate(date) {
if (isEmpty($date)) return emptyDateError();
if (isTimestamp(date)) return formatWithTimestamp(date);
if (isDateObject(date)) return formatWithObject(date);
if (isString(date)) return formatWithString(date);
throw new DateFormatException(date);
}The difference is immediate: with guard clauses the code is far easier to read, and easier to maintain, for you and for your colleagues.
Conclusion
Guard clauses and validation checks both validate input. The difference comes down to whether the invalid input is expected and part of the application, or genuinely unexpected. Only use exceptions for the unexpected cases, and use ordinary validation logic for the problems you already know incoming data can have.


