DEV Community

Cover image for Code Smell 206 - Long Ternaries
Maxi Contieri
Maxi Contieri

Posted on • Originally published at maximilianocontieri.com

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

  1. Extract the method guards

Refactorings

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
Enter fullscreen mode Exit fullscreen mode

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();
Enter fullscreen mode Exit fullscreen mode

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

More Info

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


This article is part of the CodeSmell Series.

Top comments (0)