How to structure your code for readability
Dan Bar-Shalom
Posted on January 22, 2024
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.
Posted on January 22, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.