| ▲ | quotemstr 5 hours ago | |||||||
The tech industry is full of brash but lightly-seasoned people resurrecting discredited ideas for contrarianism cred and making the rest of us put down monsters we thought we'd slain a long time ago. "Defensive programming" has multiple meanings. To the extent it means "avoid using _ as a catch-all pattern so that the compiler nags you if someone adds an enum arm you need to care about", "defensive" programming is good. That said, I wouldn't use the word "defensive" to describe it. The term lacks precision. The above good practice ends up getting mixed up with the bad "defensive" practices of converting contract violations to runtime errors or just ignoring them entirely --- the infamous pattern in Java codebases of scrawling the following like of graffiti all over the clean lines of your codebase:
That's just noise. If someArgument can't be null, let the program crash.Needed file not found? Just return ""; instead. Negative number where input must be contractually not negative? Clamp to zero. Program crashing because a method doesn't exist? if not: hasattr(self, "blah") return None People use the term "defensive" to refer to code like the above. They programs that "defend" against crashes by misbehaving. These programs end up being flakier and harder to debug than programs that are "defensive" in that they continually validate their assumptions and crash if they detect a situation that should be impossible. The term "defensive programming" has been buzzing around social media the past few weeks and it's essential that we be precise that 1) constraint verification (preferably at compile time) is good; and 2) avoidance of crashes at runtime at all costs after an error has occurred is harmful. | ||||||||
| ▲ | kstrauser 3 hours ago | parent [-] | |||||||
For a second I thought you were advocating for something of those, and I had a rant primed up. Yes. Defensively handle all the failure modes you know how to handle, but nothing else. If you're writing a service daemon and the user passes in a config filename that doesn't exist, crash and say why. Don't try to guess, or offer up a default config, or otherwise try to paper over the idea that the user asked you to do something impossible. Pretty much anything you try other than just crashing is guaranteed to be wrong. And for the love of Knuth, don't freaking clamp to zero or otherwise convert inputs into semantically different value than specified. (Like, it's fine to load a string representation of a float into an IEEE754 datatype if you're not working with money or other exact values. But don't parse 256 as 255 and call it good enough. It isn't.) | ||||||||
| ||||||||