Return Early, Return Often
Aug 06, 2019
The cognitive load introduced by having a single return statement in a function (normally accompanied by a result
variable) is often underappreciated, but luckily with a little refactoring it's fairly easy to resolve.
I was working in a project recently when I came across some code similar to this (domain has been changed for privacy, but the logic is the same):
const isDuplicateId = (id: string) => {
let duplicate = false;
const employee = getEmployee(id);
if (employee !== null) {
duplicate = true;
} else {
const manager = getManager(id);
if (manager !== null) {
duplicate = true;
} else {
const admin = getAdmin(id);
if (admin !== null) {
duplicate = true;
}
}
}
return duplicate;
};
It's not particularly difficult to read, but the single return
statement muddies the waters slightly.
In the first if
block, it isn't clear that true
is going to be the return value just from that statement alone, because there isn't a return
at that point. The reader also need to consider the else
statement, and check further down the method to make sure that duplicate
isn't modified anywhere else. The same applies for the two other if
statements.
This means that the task of mentally tracing the code and figuring out how it behaves is made a lot more difficult - if you just want to see how it behaves when employee
isn't null
, the reader needs to read the whole method just to check that it isn't doing anything.
With some return
statements, this code can be made a lot more manageable.
const isDuplicateId = (id: string) => {
const employee = getEmployee(id);
if (employee !== null) {
return true;
}
const manager = getManager(id);
if (manager !== null) {
return true;
}
const admin = getAdmin(id);
if (admin !== null) {
return true;
}
return false;
};
Now the code requires much less reading in order to understand specific behaviours. If you want to see how the code behaves when employee
isn't null
, you only need to read the first 3 lines of code (excluding whitespace).