[ Content | View menu ]

Fail Hard and Fast

Mark Mzyk | April 17, 2008

Within the code-base, as already mentioned, defensive programming can cause defects to become entrenched. Instead, we should adopt a more confident style, where code fails hard and fast.

Stop the clock, squash the bug

I heartily agree with that statement.  I think it can be reworded in this way:

Fail, then fix the failure, not the symptom of the failure.

I think we’re all taught as we learn to program that we should be defensive programmers.  It’s like driving.  You’re supposed to be a defensive driver, because should you not be, you might get into  a wreck because of the moron on the road next to you (there’s always one of those) and then, praying no one gets hurt, you have to go through the mess of getting the car repaired, insurance, etc.  Yes, there’s a reason for defensive driving.  It’s the same reason for defensive programming.

Only, in programming, unless you work for NASA, or some other critical system developer, failure isn’t going to result in someone getting hurt or in you having to shell out for a new car.

So what does it hurt to fail if an unacceptable input is passed into a function?

If you let the failure happen, you can now trace the failure back to its origin and fix it, saving much pain in the future.  By programming defensively, you allow the original cause of the failure to continue to exist in the system and to potentially cause more harm at a later date, even though you’ve prevented some harm today.

There’s also another implication of defensive programming: lack of trust.

Do programmers do bone headed things?  Yes.  Yet at some point, you have to trust your coworker, that he or she actually has some idea what they are doing, and that they will do the right thing.  If you don’t trust them, why are they working next to you?  I think that implies either they, or you, need to seek a relocation.

With trust in place, the system will be built faster and it will be built better.  Why?  You won’t be spending time programming defensively, but will instead be getting things done.

So fail already.  It will lead you to success.