Refactoring: Resource management

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

Error management

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

The flaw

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

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

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)
}

Software engineer for three decades, I would like to share my memory. https://www.javarome.com

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