DEV Community

Discussion on: Is “Defensive Programming” actually healthy?

Collapse
 
nepeckman profile image
nepeckman

I agree that done well, defensive programming is helpful. Being mindful of the future is generally a good thing, especially in software engineering where things change so frequently! However, in the interest of making this a more interesting discussion, I posit defensive programming can be done wrong. I once contributed to a JavaScript codebase that took defensive programming to an extreme. Every function checked that all the arguments were the right type and were non null. While this might be desirable for some functions (especially functions consuming user input or exposed in an api), the proliferation of defensive checks had a obfuscating effect. I couldn't tell which functions should actually expect and handle null input, and what functions had just cargo culted the checks. We structure our code primarily to communicate to our future selves and teammates. This code was hiding valuable information about the flow of data through the codebase by introducing unnecessary fear.

We later transitioned to TypeScript and deleting all of those defensive checks (replacing them with types) was very satisfying.

Collapse
 
cubiclebuddha profile image
Cubicle Buddha

Omg this was totally the way that I wrote JS before TypeScript was invented:

Every function checked that all the arguments were the right type and were non null.

And this was also me:

We later transitioned to TypeScript and deleting all of those defensive checks (replacing them with types) was very satisfying.

It’s so nice to meet others who have had similar journeys. And thank you for sharing your perspective on the clutter of duck typing. I never thought of that so it was really valuable to hear. :)