Defensive programming is so groovy

Copasetic tests verify every possible path through a method– sunny day and rainy scenarios; however, in the Age of Aquarius we’re lucky enough to have a test– consequently, one can scan a cornucopia of test suites to discover a false sense of security.

You: This method has 100% code coverage?

Them: Yes.

You: It’s bug free?

Them: Totally.

You: What happens if I pass in null?

Them: null would never be passed in.

Because it’s your bag (and not theirs), you write a hip test that passes in null and voila! that 100% covered method isn’t 100% reliable.

Of course, handling this condition is as old as programming itself (even older than disco!)– checking for null before doing anything. But, checking for null is a bit verbose, not to mention fairly repetitive if it’s pervasive across a series of methods. Those dancers familiar with aspect oriented programming, or AOP, will recognize this as a crosscutting concern, meaning that defensive programming techniques span horizontally across a code base.

If AOP isn’t your bag though, you can always employ Groovy’s ? construct, which still results in repetitive code, however, it’s dramatically less verbose than typical if/then/else conditionals.

For example, take this hip getter on a JavaBean-like Java class:

public String getGenre() {
 if(genre != null){
  return genre.toUpperCase();
 }else{
  return null;
 }
}

The guard conditional now effectively removes the chance of a NullpointerException should the bean be initialized without a genre property. With Groovy, however, I can replace the entire conditional with one operator, baby.

Groovy’s ? operator is an effective safety net that you can apply before calling a method on an object you suspect could be null. For example, the above code is guarding against the bogue genre variable– with Groovy then, before I attempt to invoke the toUpperCase method, I can simply place a strategic ? and thus forego any conditionals like so:

def getGenre(){
 "${genre?.toUpperCase()}"
}

In essence, the two code examples are exactly the same (save for a few minor keystroke differences)– either an all capitalized String instance is returned or null is returned. Consequently, if you find yourself writing a lot of defensive code (and your bag isn’t AOP) then consider applying Groovy’s ? operator– it’ll save you a couple lines of code and a few NullpointerException headaches, man!

10 Responses to “Defensive programming is so groovy”

  1. on 18 Feb 2008 at 5:54 pm Guillaume Laforge

    Why even putting everything inside a GString? You just need to return genre?.toUpperCase().

    This trick is also more appealing when you have to go through some deep objectgraph. So instead of nested if / else, you can just return car?.make?.name?.toUpperCase() withouth having to check whether car is null, and make is null, and name is null, etc.

  2. on 18 Feb 2008 at 6:08 pm Andy

    Good call, sir– I haven’t the slightest clue why I am working with a GString in that method. Thanks for pointing that out, man, and yeah– the deep object graph example is right on.


  3. […] Original post by Andy […]

  4. on 19 Feb 2008 at 1:32 pm Adam Kruszewski

    What I have to write if I would like to return empty (ie. “”) gstring in place of null in your example?

    Don’t you think it should make a difference to write:
    “${genre?.toUpperCase()}”
    and
    ${genre?.toUpperCase()}

    The first case, in my opinion, should return empty GString.
    The second should return null.
    If both cases return null then the GString decalaration is a little bit misleading.

    Cheers,
    a.

  5. on 19 Feb 2008 at 4:29 pm Randy Hudson

    Adam, one way of acccomplishing what you want is to use the ?: (’elvis’) operator:

    genre?.toUpperCase() ?: ”

    This operator (new to 1.5) returns the first expression unless it’s a false (null, 0, empty, false) value, else the second expression.

    Also note that “${null}” evaluates to ‘null’, not ”.


  6. […] ? operator saves you from constantly having to check for null. Andrew Glover has a good example of Defensive Programming with Groovy over at The Disco Blog […]

  7. on 20 Feb 2008 at 4:19 am Jason Rudolph

    Guillaume, Guillaume, Guillaume - *Please* don’t encourage people to write code like that. While this operator is indeed handy at times, I’d only trust about 2% of all programmers to use it appropriately. (To be clear, I’m not saying that Groovy shouldn’t offer this method. It absolutely should be there. I’m simply saying that 98% of the people that employ it will do so poorly and in a manner that compensates for generally shoddy code.)

    Andy - You’re right on about the false confidence of 100% code coverage. (Jay Fields has a good post on this topic.) Bottom line: When it’s that easy to get 100% test coverage and still have buggy code, there’s simply no excuse for having anything less that 100% coverage. In fact, one could argue that 100% coverage is for underachievers. ;-)


  8. […] back to the getGenre method on the Song class, it turns out that Groovy also has a handy syntax for null pointer safety, consequently, I can simply that method even […]

  9. on 24 Apr 2008 at 9:26 am it-bbr

    It´s so easy to be save - but is utterly unused


  10. […] operating with ternaries One of my favorite features in Groovy is its hip ? operator, which facilitates Nullpointer navigation safety– while this feature isn’t available […]

Trackback this Post | Feed on comments to this Post

Leave a Reply