Clean up nested if-statements with ease.
) Cyclomatic complexity is defined as the number of linearly independent paths through the code, so you are increasing the complexity of your code every time you add an if-statement!
In this post, I show you a simple example of improving code by abstracting nested if-statements.
Note: there are probably far better ways of doing the following, but I went with the simplest way I could think of.
The Ugly Code
I was reading about an algorithm that converts numbers to their English names (110 -> one hundred and ten), the book gave me a code snippet made up of an unreadable nested if statements:
) Can you understand what the code is doing? it took me a while but it is simply formatting the hundreds part of the code then it moves to formatting the tens and ones, the details are irrelevant (get the entire code on my Github).
The Good Code
How to improve the above code snippet? I used two things:
- ternary if statement
- moving related parts of code to their own methods
and the result:
) In my humble opinion; this code is far easier to understand because instead of if statements we get meaningful function names.