Overly defensive programming

Carl Vitullo
6 min readFeb 16, 2018

(Also republished on my personal blog)

I recently asked a coworker why a certain check was being done, and he answered with a shrug and said, “Just to be safe.” Over my career, I’ve seen a lot of code written just to be safe. I’ve written a lot of that code myself! If I wasn’t sure if I could rely on something, I’d add a safety check to prevent it from throwing an exception.

To give some examples, I mean idioms like providing unnecessary default values.

axios.get(url).then(({ data }) =>
// If the response doesn't have a document, use an empty object
this.setState({ document: data.document || {} });
})

Or checking that each key exists in deeply nested data.

render() {
const { document } = this.state;
const title = document &&
document.page &&
document.page.heading &&
document.page.heading.title;
return <h1>{title}</h1>
}

And many other idioms. Idioms like these prevent exceptions from being thrown. Used without care, suppressing an exception is like hanging art over a hole in the wall.

--

--