When writing code, it is often tempting to wrap the main flow inside multiple if statements in order to validate that certain conditions are met.
For example, let's say I'm writing a simple method that returns the length of a string. It might look like this:
function getLength(str) {
if (typeof str === 'string') {
return str.length()
}
throw new Error('parameter must be a string')
}
While this guards against unexpected parameter types, the main flow is enclosed within an if statement. A more refined approach looks like this:
function getLength(str) {
if (typeof str !== 'string') {
throw new Error('parameter must be a string')
}
return str.length()
}
On the surface, the distinction may appear subtle, yet the structure of the code makes the main code flow more readable.
This advantage becomes even more apparent when there are multiple exclusion flows. You can turn this nested structure:
function foo() {
if (/*condition A*/) {
if (/*condition B*/) {
if (/*condition C*/) {
/*main flow*/
}
/*handle !condition C*/
}
/*handle !condition B*/
}
/*handle !condition A*/
}
into this:
function foo() {
if (/* !condition A */) {
/*
handle !condition A
return
*/
}
if (/* !condition B */) {
/*
handle !condition B
return
*/
}
if (/* !condition C */) {
/*
handle !condition C
return
*/
}
/*main flow*/
}
The result is cleaner and more readable code, easier to understand and maintain.
Top comments (2)
The 2nd example is not correct as whatever the condition A, B or C are, the main flow will be process, and it is not the case in the 1st example.
You are correct, thanks.
I've added
return
in eachif
block