Wednesday, May 02, 2007

8 defensive programming best practices

This article is written for PHP, but at the high level these 8 practices apply everywhere. Here they are (with comments by me). The original article has more comments and PHP specific resources.

  1. Handle unexpected conditions - of course you cannot expect every unexpected condition, but you can write code to handle things when they don't happen as expected. Even if the code just raises an error.
  2. Process external systems data properly - Instead of just assuming all input and output is correct, validate it. Be sure you are getting what you are expecting, and that what your program produces is correct. This is especially an issue with SQL and HTML injection!
  3. Test your code - Hello McFly, anyone home? You need unit tests, regression tests, UI tests, user tests, etc. Then look at what you are not testing and test that. Especially if you are releasing to the public.
  4. Monitor your site errors and act upon them - Whatever kind of development you are doing, you need to log all errors (serious and minor) and if possible centralize them. Then analyze your error logs and do something about it. When you start seeing those exceptions you put in for #1 show up, that means the unexpected happened. Now that you know what it is, you can expect it and act on it.
  5. Do not disclose errors to the users -This is huge for websites. I don't know how many times I have been using a website and it breaks and I am presented with a beautiful debug screen with all sorts of juicy details that if I were a hacker I could make use of. This is the worst with ASP/ASP.NET sites. Remove debug messages when you release - same goes for non-web development.
  6. Damage control - Make sure your program fails gracefully. Save the users data often.
  7. Backup - This is another really obvious one. First of all, use a GOOD source control system so you are backed-up during the development process. Remember to backup your database and other non-source code bits too. Then backup your users data for them. Even if you can't force them to backup their data, at least make it easy.
  8. Do what you can as you can never get defensive enough - This is like Lather, Rinse, Repeat. Once you have done all the above, refactor your code, and go through the steps again. Just be aware that things break. This goes back to #6. What can you do to make sure they don't break to bad? That is a good start.

One other point it makes is "If anything can go wrong, it will." I would not say that every worst case scenario will play out. I will however say that the more possibility for malfunction you leave, the greater the chance. Also, the more users you have, and the more time the users spend using your application, the greater the odds of any errors showing up.

What are your defensive programming best practices?

Technorati Tags: [] [] [] [] []

No comments: