IF-ELSE Sucks!

Zeeshan Ali
2 min readJun 9, 2021

Hello Guys, I am writing few lines on code refactoring.

Every programmer is already aware of IF-ELSE conditions so instead of further explaining IF-ELSE conditions, let me get to the point.

Nothing is wrong with the IF-Else or Switch blocks, but while using them we should keep at least two points in our mind.

  1. Use polymorphism if you believe that requirements may change or more blocks might be added in the future.
  2. Don’t use polymorphism when conditions perform simple tasks and there is no need to change it.

Okie! Let see how the IF-Else condition can be replaced using a simple technique in Javascript also with OOP supposed languages such as Java, C#, Typescript and so on you can use Polymorphism, Here I am trying to explain this concept only. (Polymorphism is not part of this topic)

Look at this traditional IF-Else block, it looks very simple right!
But if you look it more closely, you will find a couple of problems in this code.

  1. Fizz, Buzz, and FizzBuzz algorithms are tightly coupled altogether with the main program. (It violates the OCP and SRP Principle)
  2. When you add a new condition you will need to find the fizzBuzzProgram to modify it. (It may require testing for full IF-ELSE block).
  3. Class or program will start growing unnecessarily with IF-ELSE block.
  4. Code becomes unreadable and hard to understand, and to make it understandable, we usually add comments on each block.

We can extract and move each block logic into separate function and give it to a meaningful name that would be easier to make it readable and maintainable also that function can be reused to avoid duplications.

--

--

Zeeshan Ali

I am Zeeshan Ali, and i am Software Engineer since 2006.