Rules Hub
Coding Rules Library
Replace nested ternaries with configuration helpers
Avoid complex nested ternary operators for value selection by using a helper function that accepts a configuration object.
Bad example
| 1 | return ( |
| 2 | <a |
| 3 | className={product === 'BrandA' ? 'bg-red-500' : product === 'BrandB' ? 'bg-gray-500' : 'bg-blue-500'} |
| 4 | href={product === 'BrandA' ? '/brand-a' : product === 'BrandB' ? '/brand-b' : '/'} |
| 5 | > |
| 6 | Link |
| 7 | </a> |
| 8 | ); |
Explanation (EN)
Nested ternaries make the code hard to read and force you to repeat the conditional logic for every prop. Adding a new case requires modifying every usage site.
Objašnjenje (HR)
Ugniježđeni ternarni operatori otežavaju čitanje koda i prisiljavaju na ponavljanje uvjetne logike za svaki prop. Dodavanje novog slučaja zahtijeva izmjenu na svakom mjestu korištenja.
Good example
| 1 | // Helper handles fallback logic centrally |
| 2 | function getProductValue<T>(options: { brandA?: T; brandB?: T; default: T }): T { |
| 3 | const product = window.product; |
| 4 | if (product === 'BrandA') return options.brandA ?? options.default; |
| 5 | if (product === 'BrandB') return options.brandB ?? options.default; |
| 6 | return options.default; |
| 7 | } |
| 8 |
|
| 9 | return ( |
| 10 | <a |
| 11 | className={getProductValue({ |
| 12 | brandA: 'bg-red-500', |
| 13 | brandB: 'bg-gray-500', |
| 14 | default: 'bg-blue-500', |
| 15 | })} |
| 16 | href={getProductValue({ |
| 17 | brandA: '/brand-a', |
| 18 | brandB: '/brand-b', |
| 19 | default: '/', |
| 20 | })} |
| 21 | > |
| 22 | Link |
| 23 | </a> |
| 24 | ); |
Explanation (EN)
Using a helper function simplifies the call site into a declarative object map. This centralizes the logic for fallbacks and makes the component code much cleaner and easier to maintain.
Objašnjenje (HR)
Korištenje pomoćne funkcije pojednostavljuje poziv u deklarativnu mapu objekta. To centralizira logiku za 'fallback' vrijednosti i čini kod komponente čišćim i lakšim za održavanje.
Notes (EN)
This pattern is especially useful when switching themes, brands, or configurations based on a global state.
Bilješke (HR)
Ovaj obrazac je posebno koristan pri mijenjanju tema, brendova ili konfiguracija na temelju globalnog stanja.