Something that every programmer worth their salt learns to do sooner or later. While defensive driving
is mainly about protecting yourself from other people's mistakes, defensive programming is about protecting yourself from your own mistakes
, which you are almost guaranteed to make. The important thing is to catch those bug
s quickly before they can hide and become hard to track. An example:
You write a function with an integer parameter. The function only makes sense with a parameter greater than 0. But it's really only a small helper function that only you yourself will use. There is a strong impulse to say "well, I know the parameter must be positive, and nobody else uses it, so I don't need to do a sanity check and bother with all that stupid exception handling. And it'll be faster, too!"
Defensive programming means: force yourself not to be lazy, and to as much sanity checking as possible! And not just once: do redundant sanity checking!!
Why? Because you will make a stupid mistake at one point or another. And if that mistake isn't caught immediately, it will propagate, and mutate, and cause inconsistent values or data structures. The negative value that shouldn't be will enter into computations and comparisons, and if it causes sirens to go off twenty function calls down the road instead of right away, then
you will have one hell of a time backtracking to where things actually started to go wrong and find the actual bug.
Writing all that exception handling code may be an annoying chore, but it pays off when it means that you'll find a bug in five minutes instead of five hours. Don't think it can't happen to you, because it will!
of course, all of this is doubly and triply true if you're not the only person working on that piece of code...