DEV Community

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

Posted on • Originally published at maximilianocontieri.com

2

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.

Image of Docusign

Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay