We, as programmers, use to deal with 'if .. else' in our work. Although it's all working, some of them maybe complex, nested and hard to read. This can be avoided by using small blocks of code for every condition.

For example, we have a function named is_normal_car(vehicle) that returns a boolean value from a vehicle class. The function has four conditions that have to be met. The conditions are:

  • Have four tires.
  • Weight between 1500 kg and 3000 kgs.
  • Engine size between 1000 cc and 2300 cc.
  • Price between 25000 USD and 50000 USD.

The code will look like this.

None
is_normal_car() function

The readability in this code is bad. Why? Because the conditions are nested and we need to go through all conditions to get the result. Not only that, but also if we want to look at the result from a condition that isn't met, we need to look down the 'else' from that condition that is separated by more than one line. We can optimize this code to make it more readable by separating every condition into a small block of code.

None
is_normal_car() function, but better

In this code, the code readability increased. We can see the result of every condition in a shorter line. By negating every condition and set False as the return value, the code becomes more readable since we don't need to put a condition inside another condition and become nested conditions.

Let's try the function with some cases.

  • A vehicle has 3 tires. Function will return False as it doesn't meet the first condition where the tires has to be four.
  • A vehicle has 4 tires, weighs 2500 pounds, has engine size 3000, priced at 55000 USD. Function will return False as it doesn't meet the third condition where the vehicle's engine size has to be higher than or equal 1000 and lower than or equal 3000.

There are many ways to improve 'if .. else' in your code, but that's one way to do it. I hope you enjoyed and learned something from reading this article.