TL;DR: You have the important else condition on the else.
Problems 😔
Readability
Solutions 😃
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 👩❤️💋👨
Code Smell 156 — Implicit Else
We learn if/else on our first programming day. Then we forget the else
More Information 📕
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.