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).
Perform a cache lookup once per request path
Don't read the same cache key twice in one method. A single lookup-then-populate flow avoids redundant round-trips and divergent behavior between the two checks.
Bad example
| 1 | async getUser(id: string) { |
| 2 | const key = `user-${id}`; |
| 3 | const cached = await this.cache.get<User>(key); |
| 4 | if (cached) return cached; |
| 5 |
|
| 6 | // ... some work ... |
| 7 |
|
| 8 | // Redundant second lookup of the same key |
| 9 | const again = await this.cache.get<User>(key); |
| 10 | if (again) return again; |
| 11 |
|
| 12 | const user = await this.api.fetchUser(id); |
| 13 | this.cache.set(key, user, ttl); |
| 14 | return user; |
| 15 | } |
Explanation (EN)
Two reads of the same key add an extra round-trip and create two places that can drift apart in their logging or return logic, confusing future readers.
Objašnjenje (HR)
Dva citanja istog kljuca dodaju dodatni round-trip i stvaraju dva mjesta koja se mogu razici u logiranju ili povratnoj logici, zbunjujuci buduce citatelje.
Good example
| 1 | async getUser(id: string) { |
| 2 | const key = `user-${id}`; |
| 3 | const cached = await this.cache.get<User>(key); |
| 4 | if (cached) return cached; |
| 5 |
|
| 6 | const user = await this.api.fetchUser(id); |
| 7 | this.cache.set(key, user, ttl); |
| 8 | return user; |
| 9 | } |
Explanation (EN)
A single lookup at the top, then fetch-and-populate on a miss, is the canonical cache-aside flow with no duplicated reads to keep in sync.
Objašnjenje (HR)
Jedno citanje na vrhu, zatim dohvat-i-popuni kod promasaja, je kanonski cache-aside tok bez dupliciranih citanja koja treba drzati uskladjenima.