Rules Hub
Coding Rules Library
Rule priority, scope & exceptions
Use this to align rules with the senior-level structure (P0/P1/P2, scope, exceptions/tradeoffs).
Default gracefully instead of throwing on missing optional config
When an optional input is absent, fall back to a sensible default rather than throwing and crashing the whole feature.
Bad example
| 1 | function SortableList({ items, sortOptions }) { |
| 2 | const firstSortOption = Object.values(sortOptions)[0]; |
| 3 | // Crashes the whole component (and potentially the app) if the |
| 4 | // consumer simply forgot to pass sortOptions. |
| 5 | invariant(firstSortOption !== undefined, 'sortOptions must contain at least one entry'); |
| 6 |
|
| 7 | const [sortBy, setSortBy] = useState(firstSortOption); |
| 8 | return <List items={items} sortBy={sortBy} />; |
| 9 | } |
Explanation (EN)
Throwing on a missing optional value takes down the entire feature — users see nothing instead of a working list — just because one optional input was omitted.
Objašnjenje (HR)
Bacanje greske kada nedostaje opcionalna vrijednost rusi cijelu funkcionalnost — korisnik ne vidi nista umjesto liste — samo zato sto je izostavljen jedan opcionalni ulaz.
Good example
| 1 | const DEFAULT_SORT = SortOption.NEWEST; |
| 2 |
|
| 3 | function SortableList({ items, sortOptions }) { |
| 4 | // Fall back to a sensible default so the list still renders. |
| 5 | const firstSortOption = Object.values(sortOptions)[0] ?? DEFAULT_SORT; |
| 6 |
|
| 7 | const [sortBy, setSortBy] = useState(firstSortOption); |
| 8 | return <List items={items} sortBy={sortBy} />; |
| 9 | } |
Explanation (EN)
Falling back to a documented default keeps the feature usable when an optional input is missing, degrading gracefully instead of crashing.
Objašnjenje (HR)
Vracanje na dokumentirani default odrzava funkcionalnost upotrebljivom kada nedostaje opcionalni ulaz, gracefully degradira umjesto da se srusi.
Notes (EN)
Reserve hard invariants/throws for genuinely unrecoverable programmer errors where no safe default exists and continuing would corrupt data. A missing optional UI prop with an obvious default is not one of those cases.
Bilješke (HR)
Cuvaj tvrde invarijante/bacanja za stvarno nepopravljive programerske greske gdje nema sigurnog defaulta i nastavak bi pokvario podatke. Nedostajuci opcionalni UI prop s ocitim defaultom nije takav slucaj.
Exceptions / Tradeoffs (EN)
If the value is truly required for correctness and there is no safe default (e.g. a missing API key on the server), failing fast with a clear error is appropriate. Balance against prefer-null-over-defaults-for-missing-data: supply a default only for optional config where a sensible fallback is unambiguous and no consumer needs to detect absence.
Iznimke / Tradeoffi (HR)
Ako je vrijednost stvarno nuzna za ispravnost i nema sigurnog defaulta (npr. nedostajuci API kljuc na serveru), brzo padanje s jasnom greskom je u redu.