1. Defensive Programming

The best way to ensure the quality of the software you build is to design it carefully from the start.

dynamic techniques: those that involve executing the program and observing its behaviour.

static techniques: those that you use to ensure quality before you execute (by evaluating the design and by analyzing the code).

Defensive programming is an approach to increasing the reliability of a program by inserting redundant checks.

Here’s how it works: When you’re writing some code, you figure out conditions that you expect to hold at certain points in the code – invariants, in other words. Then, rather than just assuming that these invariants hold, you test them explicitly.

1.1. Guidelines

When should you write runtime assertions? As you write the code, not later.

Runtime assertions are not free.

Good programmers will typically use assertions in these ways:

  • At the start of a procedure,

  • At the end of a complicated procedure,

  • When an operation is about to be performed that has some external effect.

1.2. Catching Common Exceptions

(JVM) – already includes runtime assertions for several important classes of error:

  • Calling a method on a null object reference;

  • Accessing an array out of bounds;

  • Performing an invalid downcast.

It is good practice to catch all these exceptions!

1.3. Responding to Failure

You might feel tempted to try and fix the problem on the fly. This is almost always the wrong thing to do. It makes the code more complicated, and usually introduces even more bugs.

On the other hand, it often makes sense to execute some special actions irrespective of the exact cause of failure:

  • You might log the failure to a file,

  • and/or notify the user on the screen,

  • In a safety critical system, deciding what actions are to be performed on failure is tricky and very important.

Sometimes, it’s best not to abort execution at all.