You love ternaries too much
TL;DR: Don't use ternaries for code execution. You should read them as a math formula.
Problems
Difficult to read
Low Reuse
Low Testability
Solutions
Refactorings
Refactoring 010 - Extract Method Object
Maxi Contieri ・ Nov 7 '22
Context
When a ternary condition is used in code that contains multiple functions, it can be challenging to determine which function is being affected by the condition.
This can make it harder to identify and fix bugs, as well as to understand how the code works in general.
Sample Code
Wrong
const invoice = isCreditCard ?
prepareInvoice();
fillItems();
validateCreditCard();
addCreditCardTax();
fillCustomerDataWithCreditCard();
createCreditCardInvoice()
:
prepareInvoice();
fillItems();
addCashDiscount();
createCashInvoice();
// The intermediate results are not considered
// The value of the invoice is the result of
// the last execution
Right
const invoice = isCreditCard ?
createCreditCardInvoice() :
createCashInvoice();
// or better...
if (isCreditCard) {
const invoice = createCreditCardInvoice();
} else {
const invoice = createCashInvoice();
}
// Even better with polymorphism...
const invoice = paymentMethod.createInvoice();
Detection
[X] Automatic
Linters can detect large code blocks
Tags
- Bloaters
Conclusion
No matter where you have long lines of code, you can always refactor into higher-level functional and shorter methods.
Relations
Code Smell 149 - Optional Chaining
Maxi Contieri ・ Jul 16 '22
More Info
How to Get Rid of Annoying IFs Forever
Maxi Contieri ・ Nov 9 '20
Disclaimer
Code Smells are my opinion.
Credits
Photo by Jens Lelie on Unsplash
Thanks, Cory
The programs that live best and longest are those with short functions. You learn just how valuable all those little functions are. All of the payoffs of indirection—explanation, sharing, and choosing—are supported by small functions.
Martin Fowler
Software Engineering Great Quotes
Maxi Contieri ・ Dec 28 '20
This article is part of the CodeSmell Series.
Top comments (0)