Monday, April 28, 2008

Defensive Programming

In a post a few years ago Offensive Coding, Michael Feathers discusses the usefulness of so called defensive coding practices. People are often taught to code defensively, so that the program is more robust - right? What if the problem is addressed the other way around, - why not have the caller check that he is doing the right thing, then the need for such behavior disappears, reducing clutter, complexity and increasing readability.

I have been through this exercise many times, creating objects that return some meaningful state even though nothing, or an error, has occurred. A great example of this is to return an empty list, or an empty string - no need to check for null.

Null object is an interesting pattern, which can be used very effectively. I used to believe in defensive programming, but when you consider the effect of doing it, null checks multiply throughout code very fast. Contrast this approach by checking information at (often) a single point of entry, and I think you will agree, that these checks are unnecessary.

Read Michael's post for more on the subject, but it does irritate me when I see lots of checks for null in code - in 2008.

We need more teaching of good programming practice. I am looking forward to uncle Bob's book - Clean Code. I would like to think that any self respecting programmer would love to understand how to put together nice, clean code - in whatever language - unfortunately, I believe they are in the minority.

No comments: