Code Smell 102 - Arrow Code

Code Smell 102 - Arrow Code

Maxi Contieri
·Nov 15, 2021·

2 min read

Subscribe to my newsletter and never miss my upcoming articles

Play this article

Nested IFs and Elses are very hard to read and test

TL;DR: Avoid nested IFs. Even Better: Avoid ALL IFs

Problems

  • Readability

Solutions

  1. Extract Method

  2. Combine Boolean Conditions

  3. Remove accidental IFs

Context

In procedural code, it is very common to see complex nested ifs. This solution is more related to scripting than object-oriented programming.

Sample Code

Wrong

if (actualIndex < totalItems)
    {
      if (product[actualIndex].Name.Contains("arrow"))
      {
        do
        {
          if (product[actualIndex].price == null)
          {
            // handle no price
          }
          else
          {
            if (!(product[actualIndex].priceIsCurrent()))
            {
              // add price
            }
            else
            {
              if (!hasDiscount)
              {
                // handle discount
              }
              else
              {
                // etc
              }
            }
          }
          actualIndex++;
        }
        while (actualIndex < totalCounf && totalPrice < wallet.money);
      }
      else
        actualIndex++;
    }
    return actualIndex;
  }

Right

foreach (products as currentProduct)
  addPriceIfDefined(currentProduct)

addPriceIfDefined() 
{
  //Several extracts
}

Detection

[X] Automatic

Since many linters can parse trees, we can check on compile-time for nesting levels.

Tags

  • Readability

  • Complexity

Conclusion

Following uncle bob's advice, we should leave the code cleaner than we found it.

Refactoring this problem is easy.

Relations

More Info


The purpose of software engineering is to control complexity, not to create it.

Pamela Zave


This article is part of the CodeSmell Series.

 
Share this

Impressum

Technical Opinions are my own. I don't have the revealed truth.

Software Design is a creative activity. These are hints and not rigid rules.

I write on BackEnd Business Systems and OOP Design. My advice/experience might not suit other systems.

You can write me at info(at)maximilianocontieri.com