‘if-else’ is Forbidden – why and how to reduce logic branching in your code.
Each time there is an if-else logic in your code there is some logic branching. A state is checked and based on the result from the check different path are taken. This means that two scenarios are implemented and two scenarios should be support from now on. This could quickly become a problem because the number of supported cases grows exponentially.
At the end you start from Process1 but you have 4 different cases and path that you should support. These are 4 different tests that should be written and these are for different places where things could go wrong.
The four different paths are Process 1,2,4; 1,2,5; 1,3,6; 1,3,7
Demonstration of a live example and a real production bug
We have Subscriptions in the platform. Each subscription has a max_users field that shows how many users you could add to this subscription. If max_users=1 this means you can have only one user using the subscription.
When adding people to the subscription you have two cases
- You successfully add someone to the subscription and you show a message “Success”
- The max users is reached and you show a message “Error”
The code in a simplified manner looks something like this:
if subscription.save
form.show_message "Success"
else
form.show_message "Error"
While developing we’ve changed the code for the error from form.show_message “Error” to modal_dialog.show_message “Error”
After that we’ve changed the implementation further and the code for modal_dialog.show_message “Error” was no longed called.
As a result when the use tries to add someone to his subscription, for which they’ve payed, the app freezes and nothing happens. There is no error displayed and no user is added to the subscription.
The bug occurred because with the latest changes we’ve forgot to manually check the second case of the if-else clause and there is was not test developed for this case.
How to remove the if-else clause from this code
subscription.save
message = subscription.get_save_message
form.show_message message
The subscription.save knows what message to set based on whether the subscription was successfully saved. It could set Error or it could set Success. After that we just show whatever message the subscription has to the form. If it is empty that’s great. This means no errors have occurred. subscriptions.get_save_message could be implemented in many different ways. It could be on the subscription object or another object, but this depends on the technology and framework used. But after the method save is called the message is set and there is a single flow and now branches in our code. The method form.show_message is called a single time on a single place in our code. If we change the API of this method we would change in a single place and will not forget about the second place. There is always a single scenario. Save->Show message.
Reply
You must be logged in to post a comment.