25
Clean Code (Simplify If's)
let person = {
phone: {
exists: false,
number: '+1 (555) 555-5555'
}
}
Question:
We have a 9 line function that goes three indentations deep.
We can simplify this function. The question is, how much more readable are we able to make this function?
Through six simple iterations of refactoring this function we are going to simplify this hasUSNumber function into a single line with zero indents.
1: Traditional if-else statement (with nested if)
let hasUSNumber = dude => {
if (dude.phone.exists === true) {
if (dude.phone.number.startsWith('+1')) {
return true
}
} else {
return false
}
}
2: Inverse if-else condition to remove nested if
hasUSNumber = dude => {
if (dude.phone.exists === false) {
return false
}
else if (dude.phone.number.startsWith('+1')) {
return true
}
}
3: Combine original if and nested-if statements and return early to remove else-if statement all together
hasUSNumber = dude => {
if (dude.phone.exists && dude.phone.number.startsWith('+1')) {
return true
}
return false
}
4: Directly return condition itself and remove if statement as well as one of the return statements.
hasUSNumber = dude => {
return dude.phone.exists && dude.phone.number.startsWith('+1')
}
5: Use implicit(arrow) js function, removes "return" key word and function curly brackets
hasUSNumber = dude => dude.phone.exists && dude.phone.number.startsWith('+1')
6: de-structure function parameter to grab the phone property allowing us to remove the need to shorten our line by removing "dude." twice within our statement"
hasUSNumber = ({ phone }) => phone.exists && phone.number.startsWith('+1')
Batta bing bodda boom, just like that we've made more room in our heads and in our applications.
Starting function
hasUSNumber = dude => {
if (dude.phone.exists === true) {
if (dude.phone.number.startsWith('+1')) {
return true
}
} else {
return false
}
}
Ending function
hasUSNumber = ({phone}) => phone.exists && phone.number.startsWith('+1')
We simplified 9 lines down to 1 line, 3 indents down to 0 indents, and 181 characters down to 74 characters.
The crazy part is that refactor opportunities to simplify if statements like this happen ALL OF THE TIME in reactjs, vuejs, angular, and just about any front-end project!
Keep your eyes peeled and you'll be saving your project, team, that brain of yours thousands of lines of code!
Overview of the refactoring tricks We Used
Inverse conditional check
Refactor
if ($x === true)
To
if ($x === false)
-
Combine nested if's into one statement using && operator
Refactor
if ($x === true)
if ($y === true)
To
if ($x === false && $y === false)
- Return condition itself directly instead of true if that condition is true
Refactor
```js
if ($x === true) {
return true
} else {
return false
}
```
To
return $x
Imagine doing this kind of refactor 50 times throughout a project. You'll have a huge impact!
25