Rules Hub
Coding Rules Library
Prefer readable steps over complex single-line returns
Avoid dense one-liners involving multiple logic branches or string manipulations; break them into distinct, named steps for clarity.
Bad example
| 1 | function getTrackingUrl(url: string): string { |
| 2 | // Complex nested ternaries and manual string concatenation |
| 3 | return `${url.startsWith('http') ? url : `//${url}`}${url.includes('?') ? '&' : '?'}source=newsletter`; |
| 4 | } |
Explanation (EN)
This one-liner attempts to normalize the protocol, check for existing query parameters, and append a new one all at once. It is visually dense, hard to debug, and prone to syntax errors like missing delimiters.
Objašnjenje (HR)
Ovaj jednolinijski kod pokušava istovremeno normalizirati protokol, provjeriti postojeće parametre i dodati novi. Vizualno je zbijen, težak za debugiranje i podložan sintaksnim greškama poput zaboravljenih delimitera.
Good example
| 1 | function getTrackingUrl(url: string): string { |
| 2 | // 1. Separate base URL and existing query |
| 3 | const [baseUrl, query] = url.split('?'); |
| 4 | |
| 5 | // 2. Use standard API to manage params |
| 6 | const params = new URLSearchParams(query); |
| 7 | params.set('source', 'newsletter'); |
| 8 |
|
| 9 | // 3. Normalize protocol |
| 10 | const safeBaseUrl = url.startsWith('http') ? baseUrl : `//${baseUrl}`; |
| 11 |
|
| 12 | // 4. Reconstruct readable URL |
| 13 | return `${safeBaseUrl}?${params.toString()}`; |
| 14 | } |
Explanation (EN)
Breaking the logic into steps makes the code self-documenting. Using `URLSearchParams` handles edge cases (like encoding) automatically, and separating the protocol check makes the flow obvious to future readers.
Objašnjenje (HR)
Razdvajanje logike u korake čini kod samoobjašnjavajućim. Korištenje `URLSearchParams` automatski rješava rubne slučajeve (poput kodiranja znakova), a odvajanje provjere protokola čini tijek jasnim za buduće čitatelje.