paint-brush
How to Get Rid of Annoying IFs Foreverby@mcsee
3,054 reads
3,054 reads

How to Get Rid of Annoying IFs Forever

by Maximiliano ContieriNovember 8th, 2020
Read on Terminal Reader
Read this story w/o Javascript
tldt arrow

Too Long; Didn't Read

Most IF sentences are coupled to accidental decisions. This coupling generates ripple effect and make code harder to maintain. Ifs open doors to even worse problems, like switches, cases, defaults, return, continue and breaks. They make algorithms darker and force us to build accidentally complex solutions. Part II: Create a Polymorphic Hierarchy for every IF condition (if it doesn’t already exist). Move every IF Body to the former abstraction. Replace IF Call by polymorphic method call.

Company Mentioned

Mention Thumbnail

Coins Mentioned

Mention Thumbnail
Mention Thumbnail
featured image - How to Get Rid of Annoying IFs Forever
Maximiliano Contieri HackerNoon profile picture

Why the first instruction we learn to program should be the last to use.

Nobody uses GOTO instruction anymore and few programming languages still support it.

We have matured and confirmed spaghetti code is unmaintainable and error prone. Structured Programming solved that problem years ago.

We got rid of the sentence thanks to Edsger Dijkstra’s incredible paper: Go To Statement Considered Harmful.

Next evolution step will be removing most IF statements.

IFs/Cases and Switches are GOTOs disguised as structured flow.

Our tool will be Object Oriented Programming principles.

Photo by Przemysław Bromberek in Pixabay

The Problem

Most IF sentences are coupled to accidental decisions. This coupling generates ripple effect and make code harder to maintain.

Coupling: The One and Only Software Designing Problem

Ifs are considered as Harmful as GOTOs.

If sentences violate open/closed principle. Our designs will be less extensible and closed to extension.

What is more, Ifs are open doors to even worse problems, like switches, cases, defaults, return, continue and breaks.

They make our algorithms darker and force us to build accidentally complex solutions.

There Are No Silver Bullets For This Werewolf

People out of software development cannot explain why we use this branching sentence. This is a code smell.

How to Find the Stinky Parts of Your Code (Part I)

Solutions

Before we move on and remove IF sentences we should decide if its an essential one or an accidental If.

To check this out we will look for answers in real world through bijection.

The One and Only Software Design Principle

Essential Ifs

Let’s see an essential IF statement

We should decide whether to remove this if sentence or not. 

We must understand whether it is represents a business rule (essential) or an implementation artifact (accidental).

In the case above we will honor our bijection. So we will NOT replace the if.

People In real world describe age constraints in natural language using IFs

Accidental Ifs

Let us dive now into bad IFs.

The movie rating IF is not related to a real world If but to accidental (and coupled) implementation.

Our design decision was to model ratings with strings.

This is a classic neither open to extension, nor closed to modification solution.

Let’s see what happens with new requirements.

We can detect some Code Smells:

  1. Code is polluted with IFs.
  2. A default statement is missing.
  3. New ratings will bring new IFs.
  4. The strings representing ratings are not first class objects. A typo will introduce hard to find errors.
  5. We are forced to add getters on Movies to take decisions.

The Recipe

Let’s fix this mess with these steps:

1 — Create a Polymorphic Hierarchy for every IF condition (if it doesn’t already exist).
2 — Move every IF Body to the former abstraction.
3 — Replace IF Call by polymorphic method call.

On our example:

With this outcome:

1. Code is polluted with IFs

We should add no more IFS. Extending the model will be enough.

2. A default statement is missing

In this case default behaviour is not needed since exceptions break flow. In many times a Null Object will be enough.

3. New ratings will bring new IFs

We will be address it with polymorphic new instances.

4. The strings representing ratings are not first class objects. A typo will introduce hard to find errors.

This is hidden in Ratings implementation.

5. We are forced to add getters on Movies to take decisions.

We will clear this favoring Demeter’s law.

Breaking this collaboration chain:

Rating is private so we don’t break encapsulation.

As a consequence we are safe to avoid getters.

Nude Models - Part II : Getters

Applying the recipe to all IF conditions

Now we have the secret formula we can go further and try to remove the essential IF condition related to age.

We replaced all IFs. In the later case using Double Dispatch Technique

We used our formula and it worked. But there’s a smell of over design.

  1. Classes representing Ages are not related to real concepts on our model.
  2. Model is too complex.
  3. We will need new classes related to new age groups.
  4. Age groups might not be disjoint.

We should avoid the last design and set a clear boundary between essential and accidental ifs.

A Good design rule is to create abstractions if they belong to the same domain (movies and ratings) and don’t do it if they cross domains (movies and ages).

Do Ifs stink?

According to evidence shown above. We should consider many IFs to be a code smell and tackle them with our recipe.

Replace Conditional with Polymorphism

Why this is happening?

This article (and many others) recommend avoiding most IF sentences. This will be very hard for all developers very comfortable with its usage.

Remember, Laziness and hidden assumptions are very rooted on our profession. We have been (ab)using IFs for decades and our software is not the best version of it. 

This is a root cause analysis of a serious SSL defect on IOS caused by a lazy case:

Reflections on Curly Braces – Apple’s SSL Bug and What We Should Learn From It

This article’s thesis suggests there’s a correlation between IFs/Switch/Case and defects.

You should give a try and avoid IF conditionals.

Conclusions

With this simple technique we will be able to remove, in a procedural way, all accidental ifs. 

This will make our models less coupled and more extensive.

Null object pattern is a special case of this technique. We will be able to remove all NULLs since:

NULL ifs are always accidental.

NULL: The Billion Dollar Mistake

Credits

We have been using If removal technique at Universidad de Buenos Aires for several years. Kudos to all my fellow teachers for all the experience we gathered together with it.

Part of the objective of this series of articles is to generate spaces for debate and discussion on software design. 

We look forward to comments and suggestions on this article.