Month: March 2007

What defensive programming is and isn’t

This is a tech rant so ignore it if you are’t interested.

Defensive Programming

First, a definition (my understanding):

Defensive Programming means:

  • Not trusting the inputs to your methods/modules and validating them – throwing exceptions for unexpected input.
  • Every if should have an else. This is a caricature on my part, a more pragmatic/sensible approach is if you have a lot of if … else if … or a case statement, always put a trailing else or default that throws an exception if you think you have handled every valid case.

This is programming by contract/invariant under another guise, perhaps a little simpler. The second point can be a total pain if you use testing tools that insist on testing every path through the code, because you have to somehow pass invalid input through.

Look at the following allegedly defensive code. I would argue that this is not defensive, because it does nothing with the invalid input:

void bing(LogObject logger) {
    if (logger == null) {
        System.err.println(“logger was null”);
    }
    LocalLog log = logger.getLocal(“bing”);
    // … blah
}
 

So … you’ve logged that the logger is null but carried on to where you’d get a null pointer exception. Why? Either throw an exception, or let the exception throw itself when the getLocal method is called. I have spent most of the last 2 days removing this kind of nonsense from thousands of lines of code. Let’s look at another example:

boolean isSet(String testString)
{
    if (testString == null)
    {
        return false;
    }
    return (testString != null && testString.equals(Constants.ON)) ? true : false;
}

Assume  that Constants is a class that has some string constants defined in it.

I want to kill you! NOW! This is one of the worst examples I’ve seen of just not thinking properly. The defensive part is trying to handle the potential null, but it has been done in a really idiotic way:

  • Why test for nullity twice? Will something change the value of the object reference before it gets to the return statement? Is the Java virtual machine inhabited by pixies that change what an object reference points to between statements just for fun?
  • The expression inside the brackets by the return statement is already a boolean – why use the conditional expression?

if ( true ) return true ; else return false ;

Are you insane? I’ve seen this a lot in Oracle PL/SQL code as well. A boolean is a boolean is a boolean. 

  • If you have read Effective Java you will know that  the equals method tests for nullity in the passed object anyway. The problem is the potentially null testString will not have an equals method. You do trust that your own constants are not null,  pixies excepting. So rephrase to

return Constants.ON.equals(testString)

This is defensive because it handles the null case and it also handles all of the cases where what has been passed is’t a string (not likely in this scenario though). It’s also clean and not obscured by silliness. This leads to a common Java idiom where you always put the constant first and call its equals method, rather than the more natural passed object.

Stop returning null

A really stupid Java idiom is returning null if you’ve hit some kind of error condition, rather than throwing an exception. I’ve seen reams of this nonsense:

        try {
            // some really dangerous operation
        }
        catch ( Exception e )
        {
            // Which one of the 5 exceptions was it? you may want to handle them differently
            e.printStackTrace(System.err) ; // least it was logged somewhere !!

            return null ; // or maybe a runtime exception??
        }

Just propagate the exception or roll your own generic one for your app and throw it after encapsulating the real one. This also means the code that relies on you has to keep checking for nullity or throw random null pointer exceptions. This is inexcusable laziness and results in code like I showed before that tests for nullity all the time. Without an exception we don’t know what the nullity means, so we can’t fix it without dredging through the code (which may not even be ours) and put print statements everywhere. Usually these statements are not deleted and everything starts to bloat, especially your log files. Using nulls like this breaks the contract with the caller of the method. Exceptions are part of the contract. The user can choose to ignore them, but you kept your word with them.

So, stop returning null, please. If it’s an error then let it be one. Returning null breaks the encapsulation, because you don’t know what happened without having to go into the offending code.

If you are working with Strings, and you think it’s OK to return an empty string (as in a find method that did’t, say) RETURN AN EMPTY STRING!!! How radical is that? None of this crap

String myVar = params.get(“myVar”) ;

myVar = (myVar != null)?myVar:”“

Which I have written. J2EE designers, yes, I hate you for wasting my time. I end up writing a helper function to encapsulate this nonsense every time. 

Why has this site changed and other stuff

Blog city have changed the way they do the sites and here we have the least worst option I could find. I lke the trimmed head. Anyway, enough of that.

Ruby on Rails

Still like this environment a lot. I feel a bit ahead of the curve in that it’s still relatively small group of developers using it. I like the Ruby language itself as well. I’ve been using eclipse for rails. http://www.napcs.com. You have to do some hand cranking to set up things like calling rake tasks and starting WEBrick. I have’t had a look at rad rails which is also based on eclipse, mainly because the eclipse project settings directories fight with one another and it whines about plugins. I may set up a different Windoze user to try Rad rails – if I can be bothered.

Eclipse

I’ve finally got used to Eclipse. At work I have managed to get it to show a black background after a big fight with it and then managed to lose the settings when deleted stuff by accident. Really glad I followed my own advice and tar-d up my working directory once I’d got a build running, or it would have been a bit tedious. I’ve decided to go with just stopping everything being screaming white and see how that goes. Vim has themes and you can just pick one – why Eclipse is so far behind is beyond me, seeing as the world uses it. I’ve done some reading and this Microsoft/Apple crap about making your monitor look like a piece of paper is very bad for your eyes. The version of eclipse that ships with Eclipse for Rails does’t allow you to colour the text for scriptlets and everything went a bit black until I realised. So I’ve gone for the not-white option at home too.

Work

Bit tired of some of the silliness and the lack of planning. We’ll see.

Archive Fragments

Got some more of this edited/written. I need to think about it and do some planning, which is what I always say.

Even when I’m tired my brain keeps working

Spent a lot of the weekend in bed fighting off a virus that made me really tired. Glad I take supplements, one of the guys at work was off for a week and came back coughing like a 50 a day smoker. I think I got off lightly 

Recast the first 50 pages of Archive Fragments, looking good and tight now. I’m about a fifth of the way through the Rails book as a work book and about half just reading it.

Finished Absolution Gap – cracker of a book, really enjoyed it. It’s always interesting to read stories that make you think about what might happen if people could live for 500 years – what their perspectives would be and so on. Love the idea of the brain being enhanced to run more quickly and go into the quantum. 

Work is sort of fun because it’s new.

<java tech speak> 

We’ve been chasing an irritating bug with the framework we use to build our app. In essence the guys wrote their own IPC using sockets and if a random packet touches one of the sockets they are using it causes an out of memory error which kills sessions and randomly breaks things. A simple config change to use RMI instead, and up the memory to a better aribitrary value from the 100MB default. Bug’s been there for ever but we only just hit it. It took 6 weeks of effort to find an issue our framework supplier knew about already. Sigh.

Did some interesting reading around eden memory and so on, plus Java 1.5 has some sort of elective memory management which is in fact disabled in the app we use. Student’s T test, statistics, rah! Nearly 20 years since I did any of that stuff.

One really annoying thing about the app we are using is that in it’s “raw” state you have to rebuild the whole thing and then redeploy it every time, which takes around 10 minutes. Reminds me of the old days when I was writing COBOL – but I wo’t bore you with that. They also compile all of the JSP’s using Jasper in the build.xml before the deploy. Finding anything that might need to be changed is a total pain. Struts and tiles – really not sure what they give you about from even more XML files and indirection. Ruby on Rails looks better all the time. To be fair I suspect my dislike of S&T is at least partially because I have to keep rebuilding everything and they are’t visible in the eclipse environment because they deploy as part of the framework. Ugh.

If you want EL for all of the attributes of a given map in your JSP:

  <ul>
   <c:forEach var=”k” items=”${props}”>
     <li><c:out value=‘${k}’/> = <c:out value=‘${props[k]}’/></li>
   </c:forEach>
   </ul>

Anything else? Oh yes, I love eclipse but for not being able to make the background black across the whole tool. I read somewhere it’s much better for your eyes and have tried it with emacs and gvim and agree.

JAD

Java decompiler. Excellent tool that there is an Eclipse plug in for. Very useful. 

</java tech speak>

Need some kip now … oh yes. Big weekend in Bradford ahead – Rosie’s mum’s birthday and a conference. Love complication.