Refactoring: Resource management

A hand handing off keys to another hand
A hand handing off keys to another hand
Never keeps the keys of a resource

Error management

Yes, you must ensure that resources are released even when an error occurs. Hopefully most languages (including JavaScript, Java, Python) now support finally blocks that ease such “in any case” handling.

var resource = null
try {
resource = Resource.open()
resource.use()
} catch (err) {
console.error(err)
} finally {
if (resource != null) { // open() may have failed
resource.close()
}
}
  • it contains a fatal flaw.

The flaw

“But it works” may you say, as you have used it many times without a problem. Yes, it works in most cases, but not all. Actually, as Michael T. Nygard related in his excellent book Release It!:

[That code] grounded an entire globe-spanning, multibillion dollar airline company with its hundreds of aircraft and tens of thousands of employees.

Why? Because resource.close() can raise an error too. Some developers caring about this may actually make it even more cumbersome:

var resource = null
try {
resource = Resource.open()
resource.use()
} catch (err) {
console.error(err)
} finally {
if (resource != null) {
try {
resource.close()
} catch (closeError) {
console.error('Could not close', closeError)
}
}
}

The clean way

As often, the cause of problems here is a mix of responsibilities. You should not try to do two things at a time:

  • handling errors and releasing resource at the same level and in the same finally {} block.
try {                             // Error handling start
var resource = Resource.open()
try { // Resource handling start
resource.use()
} finally {
resource.close() // We know resource is there
}
} catch (err) {
console.error(err)
}
  • resource management is enclosed in error handling, so that it doesn’t need to care about errors. It only cares about using an already-acquired resource (if the acquisition fails, the code will interrupt to immediately execute the outer catch block) and so the closing block doesn’t have to wonder if the resource can be null at this time.

Software engineer for three decades, I would like to share my memory.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store