Conditional statements like if-else, else or switch are a core for any programming language. We all use it regularly, but surprisingly it is considered as a code smell in an object-oriented programming language (OOP). But when are if-statements a bad idea? And why?

Before we go deeper, let’s try to understand some of the important concepts in OOP:

  1. Single Responsibility principle
  2. Open-Closed principle
  • Single Responsibility Principle

Responsibility is a reason to change a class, and a class or a module should have only one reason for a change. The single responsibility principle states that if there are two responsibilities in a problem, they should be put in separate classes or modules. It would be a bad idea to club them both together. 

  • Open/Closed Principle

The concept of the open/closed principle is great. It states that code can be added without changing the existing code. This prevents conditions wherein a change in class also requires adapting all depending classes. 

Now let’s take an example of a class named “Animal” –

This code is clearly violating the Single Responsibility principle by having more than 1 responsibility i.e “Dog”, “Cat” and “Lion”. This is also violating the Open/Closed principle here. Let’s say you want to implement the sound of “Cat”, to do this we have to implement a new “what if” condition. 

This makes it clear that the above statement is a “code smell”, how will you solve this now? You can either restore conditional with State/Strategy or restore conditional via polymorphism. 

Read on to know more about code smell and how to resolve the backdrops

Translate »