logoalt Hacker News

metalcrow • yesterday at 9:43 PM • 4 replies • view on HN

Isn't defensive code just outright better to do? Sure if you're making scripts for single use or small one-offs, it's unneeded. But the moment you make a usable product or a library or a tool that more people use, if your code isn't defensive won't the program just be strictly worse? It's always better to avoid crashes or bugs or exploits and you need to be defensive to do that.


Replies

cowlevel • yesterday at 10:02 PM

Code with the necessary level of defense isn't defensive code, it's just code. It becomes defensive when you add too much defense. Like C programmers writing if(!ptr) return -EBADPTR; at the start of every function instead of just letting it crash.

(Yes it's technically undefined behaviour and not guaranteed to crash. In practice, an errant null does crash, producing a much more debuggable symptom than an ignored error code, and we are writing code for real compilers that actually exist.)

➕ show 1 reply
contravariant • yesterday at 10:20 PM

You need to balance this using the robustness principle by being very strict in the code you've written yourself.

If you're constantly checking the output of your own functions then something has gone wrong. Also if you're accepting really broad arguments then that's not necessarily better if only some values make sense.

If someone sends you a date of birth as a string by all means try to parse it within reason but if they send 13-14-15 you should throw an error instead of trying to figure out the typo. Even better do not accept strings but use a date type. Yes this limits your interface but it's a lot clearer on both sides.

radlad • yesterday at 9:51 PM

There are other takes. Notably, the Robustness Principle: https://en.wikipedia.org/wiki/Robustness_principle

popkkksidhd • today at 12:34 AM

No, absolutely not. If you don’t understand the ways in which your code will be used, you need to fix that. Defensive programming is just lazy - and more importantly, it’s taking on massive amounts of technical debt. Some of the worst codebases I’ve ever worked on were heavily defensive. And I mean the product they produced, not my ability to understand it (though over my career I’ve noticed a strong correlation between the two).