A Funny Java Flavoured Look at the World

Monday, December 04, 2006

Sometimes you need to write defensive code

I read a good description of this today, it said defensive programming is like defensive driving, you take responsibility for protecting yourself even if it's the other drivers fault. It's always a bit of conundrum for me, how defensive should I program my methods, classes because it's likely that I am the only person for quite a while to use it, so am I programming defensively for the benefit of others who might never use it.

That said defensive programming is not just about protecting the people who use your code it's about protecting your code so that a big explosion doesn't happen in your code (and thus you getting the blame). A good piece of defensive programming can help debugging immensely by getting nearer to where the actual problem is and not a function erroring just because it's been passed some invalid parameters.

An Example of this is protecting your code from invalid parameters/inputs. If a user can't be bothered to pass in the right inputs don't let your code try and wrestle with it. Check them variables being passed in and throw the appropriate error if they are not valid. An important point here is to make sure you document what is valid and invalid in your JavaDoc.

There are some situations where if you are writing a method inside a class that is private then you know what is going to be passed in so you don't have to write some defensive code because it's only your class which will be called the code and sometimes it's not worth the extra effort of creating the defensive code.

The reason I am blogging about defensive programming is because I used an example of it this week or should I say I had to decide to choose to write some code this week where I thought the best policy would be to return an Array which wasn't null.

In my example I was splitting up a log file in a various String arrays and in the piece of work I was doing, I had a log file and then had to split up the log file into various sections based on IP address. The IP addresses were static (in my tests anyway) so I decided to create some code split the log file into lines and then create 5 String arrays, each array filled with the lines with a certain IP address. What would I do if an IP address didn't have any lines. I decided to to return an array with nothing in

String [] myArray = {};

This meant that the next part of my code processed an array but I didn't have to worry about checking for nulls I just processed it because I knew that there was going to be a blank array rather than return null which would have meant I would have had to check for nulls.

This was one of the tips in Effective Java and it's very useful, don't return nulls they are dangerous and a nasty bug waiting to pop up later when a user manages to get some bad data into the system.





If you like this blog or and fancy something a bit less technical with some laughing thrown in then check out my other blog Amusing IT Stories. Which is a blog about funny and amusing stories from the IT environment and the office. It is a mix of news, office humour, IT stories, links, cartoons and anything that I find funny

Labels:

4 Comments:

  • The terminology you use is rather weird. In what I've seen, what you describe is a light form of design-by-contract, which is almost the opposite of defensive programming. The term defensive programming as I've seen it defined and used means that you anticipate that input might be bad, but instead of seeing the contract failure it as a hard failure (with an Assertion or IllegalArgumentException), you handle it by some replacement value.

    So here's examples of the three styles:

    // No checks, assume everything is passed ok
    double foo(double x)
    {
    ...
    double y = sqrt(x); // assume x is >= 0
    }

    // Design By Contract
    double foo(double x)
    {
    if (x < 0)
    {
    throw new IllegalArgumentException("Parameter x should be positive.");
    }
    ...
    double y = sqrt(x);
    }

    // Defensive Programming

    double foo(double x)
    {
    if (x < 0)
    {
    x = 0; // x should be positive so cap it at zero
    }
    double y = sqrt(x);
    }


    Obviously all that defensive programming in this context does, is hide a bug that would have been exposed in the DBC style. But some people seem to like it that way.

    So I really wonder where you got your definition of Defensive Programming from, since it seems to be the opposite of what I've read.

    By Blogger Wouter, at Wed Dec 06, 08:10:00 am 2006  

  • Don't know where you got that idea. DBC is a way to do defensive programming.
    What you a talking about is called 'input filtering', which is a more lenient type of defensive programming.

    By Blogger Nils, at Wed Dec 06, 01:52:00 pm 2006  

  • I agree with Nils because defensive programming is not just about checking values that are passed into a method/function it's about coping with things that might go wrong, like capturing a dodgy input and putting in a default or a value you think is useful.

    It might not be just the variables passed in that could be wrong, the state of other objects might cause an operation to fail.

    it is also passing back an emtpy array or object instead of a null.

    it's not always the right choice because sometimes you might want to throw an error at the earliest opportunity because you know there is no point coninueing

    By Blogger Hosky, at Wed Dec 06, 02:00:00 pm 2006  

  • This comment has been removed by a blog administrator.

    By Anonymous Anonymous, at Tue Oct 06, 06:16:00 pm 2009  

Post a Comment

Links to this post:

Create a Link

<< Home