Rules Hub
Coding Rules Library
Prefer enums or constants over magic strings
Replace opaque literal values (magic strings/numbers) with named constants or enums to make code self-documenting and maintainable.
Bad example
| 1 | function getPodcastStyle(id: string) { |
| 2 | switch (id) { |
| 3 | // Macro |
| 4 | case '6310b136fc3f2a001455be87': |
| 5 | return { color: '#24573c' }; |
| 6 | // Tech |
| 7 | case '672220df9d32b8a19324bdec': |
| 8 | return { color: '#000000' }; |
| 9 | default: |
| 10 | return { color: '#fff' }; |
| 11 | } |
| 12 | } |
Explanation (EN)
The code uses 'magic strings' (hardcoded IDs) inside the control flow. This forces the developer to write comments above each case to explain what the ID represents, which is prone to becoming outdated or missing.
Objašnjenje (HR)
Kod koristi 'magične stringove' (hardkodirane ID-ove) unutar kontrolne strukture. To prisiljava developera da piše komentare iznad svakog slučaja kako bi objasnio što ID predstavlja, što je podložno zastarijevanju ili greškama.
Good example
| 1 | enum PodcastId { |
| 2 | Macro = '6310b136fc3f2a001455be87', |
| 3 | Tech = '672220df9d32b8a19324bdec', |
| 4 | } |
| 5 |
|
| 6 | function getPodcastStyle(id: string) { |
| 7 | switch (id) { |
| 8 | case PodcastId.Macro: |
| 9 | return { color: '#24573c' }; |
| 10 | case PodcastId.Tech: |
| 11 | return { color: '#000000' }; |
| 12 | default: |
| 13 | return { color: '#fff' }; |
| 14 | } |
| 15 | } |
Explanation (EN)
Using an Enum (or a const object) gives semantic meaning to the IDs. The code becomes self-documenting (e.g., 'PodcastId.Macro'), removing the need for explanatory comments and centralizing the ID definitions.
Objašnjenje (HR)
Korištenje Enuma (ili const objekta) daje semantičko značenje ID-ovima. Kod postaje samo-dokumentirajući (npr. 'PodcastId.Macro'), čime se uklanja potreba za dodatnim komentarima i centraliziraju se definicije ID-ova.