DEV Community

Cover image for Code Smell 201 - Nested Ternaries
Maxi Contieri
Maxi Contieri

Posted on • Originally published at maximilianocontieri.com

2

Code Smell 201 - Nested Ternaries

Arrow Code, Nested Conditions, switches, else, and many more

TL;DR: Don't use nested IFs or nested ternaries

Problems

  • Readability

  • Default Case

Solutions

  1. Rewrite the code as an IF condition with an early return

Context

Nesting is always a problem with complexity.

We can fix it with polymorphism or early returns

Sample Code

Wrong


const getUnits = secs => (
 secs <= 60       ? 'seconds' :
 secs <= 3600     ? 'minutes' :
 secs <= 86400    ? 'hours'   :
 secs <= 2592000  ? 'days'    :
 secs <= 31536000 ? 'months'  :
                    'years' 
)

Enter fullscreen mode Exit fullscreen mode

Right


const getUnits = secs => {
 if (secs <= 60) return 'seconds'; 
 if (secs <= 3_600) return 'minutes'; 
 if (secs <= 86_400) return 'hours';   
 if (secs <= 2_592_000) return 'days';    
 if (secs <= 31_536_000) return 'months';  
 return 'years' 
}

// More declarative

const getUnits = secs => {
 if (secs <= 60) return 'seconds'; 
 if (secs <= 60 * 60) return 'minutes'; 
 if (secs <= 24 * 60 * 60) return 'hours';   
 if (secs <= 30 * 24 * 60 * 60) return 'days';    
 if (secs <= 12 * 30 * 24 * 60 * 60) return 'months';  
 return 'years' 
}

Enter fullscreen mode Exit fullscreen mode

Detection

[X] Automatic

Linters can detect this complexity using parsing trees.

Tags

  • IFs

Conclusion

We must deal with accidental complexity to improve code readability.

Relations

Disclaimer

Code Smells are my opinion.

Credits

Photo by NIKHIL on Unsplash


One of the best things to come out of the home computer revolution could be the general and widespread understanding of how severely limited logic really is.

Frank Herbert


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