This content originally appeared on Level Up Coding - Medium and was authored by Maximiliano Contieri
Code Smell 206 — Long Ternaries
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
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 03 — Functions Are Too Long
More Info
How to Get Rid of Annoying IFs Forever
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
This article is part of the CodeSmell Series.
How to Find the Stinky parts of your Code
Code Smell 206 — Long Ternaries was originally published in Level Up Coding on Medium, where people are continuing the conversation by highlighting and responding to this story.
This content originally appeared on Level Up Coding - Medium and was authored by Maximiliano Contieri
Maximiliano Contieri | Sciencx (2023-04-12T16:59:56+00:00) Code Smell 206 — Long Ternaries. Retrieved from https://www.scien.cx/2023/04/12/code-smell-206-long-ternaries/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.