Favorite (Clever) Defensive Programming Best Practices

In c++, I once liked redefining new so that it provided some extra memory to catch fence-post errors.

Currently, I prefer avoiding defensive programming in favor of Test Driven Development. If you catch errors quickly and externally, you don't need to muddy-up your code with defensive maneuvers, your code is DRY-er and you wind-up with fewer errors that you have to defend against.

As WikiKnowledge Wrote:

Avoid Defensive Programming, Fail Fast Instead.

By defensive programming I mean the habit of writing code that attempts to compensate for some failure in the data, of writing code that assumes that callers might provide data that doesn't conform to the contract between caller and subroutine and that the subroutine must somehow cope with it.


Allocate a reasonable chunk of memory when the application starts - I think Steve McConnell referred to this as a memory parachute in Code Complete.

This can be used in case something serious goes wrong and you are required to terminate.

Allocating this memory up-front provides you with a safety-net, as you can free it up and then use the available memory to do the following:

  • Save all the persistent data
  • Close all the appropriate files
  • Write error messages to a log file
  • Present a meaningful error to the user

SQL

When I have to delete data, I write

select *    
--delete    
From mytable    
Where ...

When I run it, I will know if I forgot or botched the where clause. I have a safety. If everything is fine, I highlight everything after the '--' comment tokens, and run it.

Edit: if I'm deleting a lot of data, I will use count(*) instead of just *