Rules Hub
Coding Rules Library
Prefer objects over tuples for structured data
Use objects with named keys instead of arrays (tuples) to represent structured data rows to improve readability and maintainability.
Bad example
| 1 | const invoiceRows = invoices.map((invoice) => [ |
| 2 | formatDate(invoice.date), |
| 3 | invoice.productName, |
| 4 | invoice.status, |
| 5 | invoice.amount, |
| 6 | ]); |
| 7 |
|
| 8 | // Consuming the data requires knowing the specific index |
| 9 | return ( |
| 10 | <tbody> |
| 11 | {invoiceRows.map((row, index) => ( |
| 12 | <tr key={index}> |
| 13 | <td>{row[0]}</td> {/* Date */} |
| 14 | <td>{row[1]}</td> {/* Product */} |
| 15 | <td>{row[2]}</td> {/* Status */} |
| 16 | </tr> |
| 17 | ))} |
| 18 | </tbody> |
| 19 | ); |
Explanation (EN)
Using arrays (tuples) to represent rows of data relies on implicit knowledge of index positions (e.g., index 0 is the date). This is brittle; adding or reordering columns breaks the logic and makes the code hard to read without constant reference to the mapping function.
Objašnjenje (HR)
Korištenje nizova (tuple-ova) za predstavljanje redaka podataka oslanja se na implicitno znanje o pozicijama indeksa (npr. indeks 0 je datum). To je krhko; dodavanje ili promjena redoslijeda stupaca lomi logiku i čini kod teškim za čitanje bez stalnog provjeravanja funkcije mapiranja.
Good example
| 1 | interface InvoiceRow { |
| 2 | date: string; |
| 3 | product: string; |
| 4 | status: string; |
| 5 | amount: number; |
| 6 | } |
| 7 |
|
| 8 | const invoiceRows: InvoiceRow[] = invoices.map((invoice) => ({ |
| 9 | date: formatDate(invoice.date), |
| 10 | product: invoice.productName, |
| 11 | status: invoice.status, |
| 12 | amount: invoice.amount, |
| 13 | })); |
| 14 |
|
| 15 | // Consuming data is self-documenting and type-safe |
| 16 | return ( |
| 17 | <tbody> |
| 18 | {invoiceRows.map((row, index) => ( |
| 19 | <tr key={index}> |
| 20 | <td>{row.date}</td> |
| 21 | <td>{row.product}</td> |
| 22 | <td>{row.status}</td> |
| 23 | </tr> |
| 24 | ))} |
| 25 | </tbody> |
| 26 | ); |
Explanation (EN)
Using objects (records) with named keys makes the data structure self-documenting. It allows for clearer usage in the JSX (e.g., `row.status` instead of `row[2]`), improves type safety, and makes refactoring easier since order no longer matters.
Objašnjenje (HR)
Korištenje objekata (zapisa) s imenovanim ključevima čini strukturu podataka samo-dokumentirajućom. To omogućuje jasniju upotrebu u JSX-u (npr. `row.status` umjesto `row[2]`), poboljšava sigurnost tipova i olakšava refaktoriranje jer redoslijed više nije bitan.