Saturday, February 20, 2010

Principles of defensive programming

I came about this topic while watching a course presentation. They mentioned that we should always validate the input provided by the user and the results returned by the code we didn't write (library calls).

Based on my experience I'd add using assertions to document and check for invariants within our code. Another use of assertions is when exposing an API to other parties. If there are preconditions that the calls to the API must satisfy, it's pretty effective to enforce them through assertions.

Another area to watch for is to always check the results (success status) of the function calls we make and act accordingly. Sometimes we tend to be too optimistic and assume that everything will work smoothly. This is somehow alleviated by the use of exceptions, which prevents continuing the processing under false assumptions, which usually yield unexpected results, hard to trace back to their root cause. Unless the exception is muted, that is, caught and ignored, (really bad practice) any problem surfaces quickly.

No comments: