Simplify Your Code

Hasan Alsulaiman
2 min readSep 26, 2021

Clean up nested if-statements with ease.

Photo by Brendan Church on Unsplash

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:

Bad Bad Code!

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:

  1. ternary if statement
  2. moving related parts of code to their own methods

and the result:

Good Code

In my humble opinion; this code is far easier to understand because instead of if statements we get meaningful function names.