This content originally appeared on DEV Community 👩💻👨💻 and was authored by Maxi Contieri
The first thing we read after the if the condition is the IF
TL;DR: You have the important else condition on the else.
Problems
- Readabiity
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 51 - Double Negatives
Maxi Contieri ・ Dec 24 '20 ・ 1 min read
Code Smell 156 - Implicit Else
Maxi Contieri ・ Aug 6 ・ 2 min read
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
Software Engineering Great Quotes
Maxi Contieri ・ Dec 28 '20 ・ 13 min read
This article is part of the CodeSmell Series.
How to Find the Stinky parts of your Code
Maxi Contieri ・ May 21 '21 ・ 8 min read
This content originally appeared on DEV Community 👩💻👨💻 and was authored by Maxi Contieri
Maxi Contieri | Sciencx (2022-12-17T21:57:08+00:00) ㄥ8Ɩ llǝɯS ǝpoƆ – spɹɐʍʞɔɐq ǝslƎ/ℲI. Retrieved from https://www.scien.cx/2022/12/17/%e3%84%a58%c9%a9-ll%c7%9d%c9%afs-%c7%9dpo%c9%94-sp%c9%b9%c9%90%ca%8d%ca%9e%c9%94%c9%90q-%c7%9dsl%c7%9d-%e2%85%8ei/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.