# Code Smell 206 - Long Ternaries

> 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](https://maximilianocontieri.com/refactoring-010-extract-method-object)

# Refactorings

%[https://maximilianocontieri.com/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

[Gist Url]: # (https://gist.github.com/mcsee/274faf5d13f9853f63228fa10ee45d7e)
```javascript
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

[Gist Url]: # (https://gist.github.com/mcsee/36ef3f34e5767f120dcabe8eebda1072)
```javascript
const invoice = isCreditCard ? 
                    createCreditCardInvoice() :
                    createCashInvoice();

// or better 

if (isCreditCard) {
  const invoice = createCreditCardInvoice();
} else {
  const invoice = createCashInvoice();
}

// Even better with polymorphism
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

%[https://maximilianocontieri.com/code-smell-03-functions-are-too-long]

# More Info

%[https://maximilianocontieri.com/how-to-get-rid-of-annoying-ifs-forever]

# Disclaimer

Code Smells are my [opinion](https://maximilianocontieri.com/i-wrote-more-than-90-articles-on-2021-here-is-what-i-learned).

# Credits

Photo by [Jens Lelie](https://unsplash.com/@madebyjens) on [Unsplash](https://unsplash.com/photos/u0vgcIOQG08)

Thanks, Cory 

%[https://twitter.com/housecor/status/1644872469302444033]
    
* * *

> 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_

%[https://maximilianocontieri.com/software-engineering-great-quotes]

* * *

This article is part of the CodeSmell Series.

%[https://maximilianocontieri.com/how-to-find-the-stinky-parts-of-your-code]
