Tim Williams
Jan 6, 2021

There's one principle that is overlooked article that supports using if statements. Many of the example ternary and switch statements are more difficult to read than the simple if statements that they are replacing.

Consider this; instead of replacing your if logic with inside the parentheses with the functionality abstracted into a well named function. For example, replace this:

let error = null

if (!user.token || user.inactive || user.access_level === 'comments') {

error = 'Error: You are not allowed to post comments!'

}

with this:

function canUserPostAComment (user) {

return !user.token || user.inactive || user.access_level === 'comments'

}

let error = null

if (!canUserPostComments(user)) {

error = 'Error: You are not allowed to post comments!'

}

Now the if statement provides context that lets the developer know what it should do, instead of reading through a list of conditions and trying to reason about what it should do.

Tim Williams
Tim Williams

Written by Tim Williams

I am a Web Developer passionate about new technologies, as well as time tested best practices (here’s looking at you Uncle Bob).

No responses yet