Sunday, January 20, 2008

Defensive Programming

After thinking some more about what I wrote in Small trick with Copy & Paste, I saw that that's just an example of an attitude to programming. We can call it defensive programming.

When I program, I always try to think "What can possibly go wrong here? And how can I make sure that doesn't happen?". One example is that I mess up variable names.

Another example is that copy and paste are a source of problems. If I duplicate code, and I need to change it, I may forget to change it everywhere. So, it's usually better to generalize it.

Another is that I change how a method is supposed to be used. For example, let's say I have a function:
    void sendEmail(String to, String cc,
String subject, String body)
But then I change it to
    void sendEmail(String to, String subject,
String body, String attachment)
So all callers have to change their parameters for this to work properly.

To be sure this doesn't break, it's better to rename the method:
    void sendEmailWithAttacment(String to, String subject,
String body, String attachment)
Then, the compiler will make sure it works. At least in a static language like Java. In Groovy or something you wouldn't detect this until runtime. That's why I'm not totally sold into dynamic languages, although I like Groovy a lot. If we use a dynamic language, we have to be defensive by using more unit tests.

A final example is if you fix a bug. There is always a risk that you or someone else will revert the change. How can we be sure this doesn't happen? The best way is to reproduce the bug with a unit test before fixing it. If this is too much work, at least write a comment explaining the fix.

It all comes down to admitting that I do mistakes and trying to prevent them.


Lars said...

"Defensive Programming" was not such a good title, since it's already defined (see Wikipedia).

Stephan said...

What about Domain Driven Development:

void sendEmail(
List<Receiver> to,
List<Receiver> cc,
Subject subject,
Body body)

(with some static helpers in Java like subject("My subject") it isn't much more verbose than working with strings. But it's type safe and bugs are much harder to introduce.


Stephan Schmidt ::
Reposita Open Source - Monitor your software development
Blog at - No signal. No noise.