Skip to main content

Command Palette

Search for a command to run...

ㄥ8Ɩ llǝɯS ǝpoƆ - spɹɐʍʞɔɐq ǝslƎ/ℲI

The first thing we read after the if the condition is the IF

Updated
2 min read
ㄥ8Ɩ llǝɯS ǝpoƆ - spɹɐʍʞɔɐq ǝslƎ/ℲI
M

I’m a senior software engineer loving clean code, and declarative designs. S.O.L.I.D. and agile methodologies fan.

TL;DR: You have the important else condition on the else.

Problems

  • Readability

Solutions

  1. Swap the conditions.

Context

It is not as straightforward as it appears to write IF clauses in an elegant manner.

There are lots of variants and choices.

We need to pay special attention to readability.

Sample Code

Wrong

fun addToCart(item: Any) {
    if (!cartExists()) {
        // Condition is negated
        this.createCart();
        this.cart.addItem(Item);
        // Repeated Code
    }
    else {
        // Normal case is on the else clause
        this.cart.addItem(Item);
    }
}

Right

fun addToCart(item: Any) {
    if (cartExists()) {
        this.cart.addItem(Item);
    }
    else {      
        this.createCart();
        this.cart.addItem(Item);
    }
}   

fun addToCartShorter(item: Any) {
    if (!cartExists()) {
        this.createCart();
    }
    this.cart.addItem(Item);    
}

Detection

[X] Semi-Automatic

We can find negated expressions on IF conditions and check for this anti-pattern.

Tags

  • IFs

Conclusion

We need to read code like prose.

Humans read the standard case first and the exceptional one after it.

Relations

More Info

Disclaimer

Code Smells are just my opinion.

Credits

Photo by Karol Kasanicky on Unsplash


Beauty is more important in computing than anywhere else in technology because software is so complicated. Beauty is the ultimate defense against complexity.

D. Gelernter


This article is part of the CodeSmell Series.

Code Smells

Part 1 of 50

In this series, we will see several symptoms and situations that make us doubt the quality of our developments. We will present possible solutions. Most are just clues. They are no hard rules.