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).
Release external connections in a finally block, not on the happy path
Wrap connect/use/disconnect of external resources (SFTP, DB, sockets) so cleanup always runs even when the work throws.
Bad example
| 1 | const client = new SFTPClient(); |
| 2 | await client.connect(opts); |
| 3 | const result = await doWork(client); |
| 4 | await client.disconnect(); // never runs if doWork throws -> leaked connection |
| 5 | return result; |
Explanation (EN)
If doWork() throws, the disconnect() line is skipped and the connection leaks. Over many runs this exhausts the connection pool or file handles.
Objašnjenje (HR)
Ako doWork() baci iznimku, linija disconnect() se preskace i veza ostaje otvorena. Kroz vise pokretanja to iscrpi pool veza ili file handle-ove.
Good example
| 1 | async function withSftpClient<T>(fn: (c: SFTPClient) => Promise<T>): Promise<T> { |
| 2 | const client = new SFTPClient(); |
| 3 | try { |
| 4 | await client.connect(opts); |
| 5 | return await fn(client); |
| 6 | } finally { |
| 7 | await client.disconnect(); |
| 8 | } |
| 9 | } |
| 10 |
|
| 11 | // usage |
| 12 | const result = await withSftpClient((client) => doWork(client)); |
Explanation (EN)
Putting disconnect() in finally guarantees the resource is released on both success and failure. A reusable with* wrapper keeps every call site safe by construction.
Objašnjenje (HR)
Stavljanjem disconnect() u finally jamcimo oslobadanje resursa i kod uspjeha i kod greske. Ponovno iskoristiv with* wrapper cini svako pozivno mjesto sigurnim po dizajnu.
Notes (EN)
Applies to any acquire/release pair: DB transactions, file handles, locks, sockets. Prefer a reusable wrapper over repeating try/finally at each call site.
Bilješke (HR)
Vrijedi za svaki par dohvati/oslobodi: DB transakcije, file handle-ove, lockove, sockete. Radije koristi ponovno iskoristiv wrapper nego ponavljanje try/finally na svakom mjestu.