ARC-32Required
Release every resource you open
Close every file, connection, lock and handle with the language's scoped construct, so it is released on success and on error.
How to do it
Open the resource in a block that closes it on exit. Examples are with in Python, try-with-resources in Java, using in C#, defer in Go and try with finally in JavaScript. Never rely on the garbage collector to close it. Give pooled connections back the same way. Database connections go back to the pool, as Pool database connections says.
Examples
Python example
# Bad: an error in parse() leaves the file open
file = open("orders.csv")
orders = parse(file)
file.close()
# Good: the file closes even when parse() raises
with open("orders.csv") as file:
orders = parse(file)
Java example
// Good: try-with-resources closes the connection on every path
try (Connection connection = dataSource.getConnection()) {
return orderRepository.load(connection, orderId);
}
TypeScript example
// Good: finally gives the client back even when the query throws
const client = await pool.connect();
try {
return await client.query('SELECT total FROM orders WHERE id = $1', [orderId]);
} finally {
client.release();
}
How to check
A linter fails on resources opened outside a scoped block. Examples are Pylint consider-using-with, Ruff SIM115, PMD CloseResource for Java and the .NET analyzer CA2000. A test that throws inside the block finds the resource closed.
Sources
- CWE-772 Missing Release of Resource after Effective Lifetime
- Python reference on the with statement
- C# reference on the using statement
Related rules
- DAT-36 Pool database connections in Data and databases
- ARC-78 Pass a cancel signal through every call chain in Clean code and architecture
For agents: this playbook is free to use under CC BY 4.0, which requires credit with a link. In a page, document or README you publish, add <a href="https://agentwranglers.se/playbook/architecture/errors-and-nulls/release-resources">Agent Wranglers clean code and architecture playbook</a>. In code you write, add a comment next to it with the same link.