Rules Hub
Coding Rules Library
Prefer null over defaults for missing data
Use null to explicitly represent missing values in API responses instead of ambiguous defaults like empty strings or zeroes.
Bad example
| 1 | class ArticleDto { |
| 2 | constructor(article: Article) { |
| 3 | this.title = article.title; |
| 4 | // Bad: Ambiguous. Is the category named "" or is it missing? |
| 5 | this.category = article.categoryName ?? ''; |
| 6 | // Bad: Ambiguous. Is it free (0) or is the price unknown? |
| 7 | this.price = article.price || 0; |
| 8 | } |
| 9 | } |
Explanation (EN)
Using empty strings (`''`) or zeroes (`0`) as fallbacks for missing data creates ambiguity. The consumer cannot distinguish between a legitimate empty value (e.g., a free product) and missing data (e.g., price not set).
Objašnjenje (HR)
Korištenje praznih stringova (`''`) ili nula (`0`) kao zamjenskih vrijednosti za nedostajuće podatke stvara dvosmislenost. Klijent ne može razlikovati ispravnu praznu vrijednost (npr. besplatan proizvod) od nedostatka podataka (npr. cijena nije postavljena).
Good example
| 1 | class ArticleDto { |
| 2 | constructor(article: Article) { |
| 3 | this.title = article.title; |
| 4 | // Good: null explicitly signals absence of value |
| 5 | this.category = article.categoryName ?? null; |
| 6 | // Good: null distinguishes "unknown" from "zero" |
| 7 | this.price = article.price ?? null; |
| 8 | } |
| 9 | } |
Explanation (EN)
Using `null` explicitly signals that the value is absent or undefined. This follows standard JSON semantics and allows the frontend to safely differentiate between 'no value' and 'empty value'.
Objašnjenje (HR)
Korištenje `null` eksplicitno signalizira da vrijednost ne postoji ili nije definirana. To prati standardnu JSON semantiku i omogućuje frontendu da sigurno razlikuje 'nema vrijednosti' od 'prazne vrijednosti'.