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

> 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

```kotlin
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

```kotlin
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

%[https://maximilianocontieri.com/code-smell-51-double-negatives] 

%[https://maximilianocontieri.com/code-smell-156-implicit-else] 

# More Info

* [Know the Code](https://knowthecode.io/if-else-backwards-code-pattern)
    

# Disclaimer

Code Smells are just my [opinion](https://maximilianocontieri.com/i-wrote-more-than-90-articles-on-2021-here-is-what-i-learned).

# Credits

Photo by [Karol Kasanicky](https://unsplash.com/@karolkas) on [Unsplash](https://unsplash.com/s/photos/upside)

---

> 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*

%[https://maximilianocontieri.com/software-engineering-great-quotes] 

---

This article is part of the CodeSmell Series.

%[https://maximilianocontieri.com/how-to-find-the-stinky-parts-of-your-code]
