Fork me on GitHub

LD.

Music, software, life… and stuff.

[ Twitter ] [ GitHub ] [ Linked In ]

Closures for readability

This is really just common sense and all the cool kids are probably already doing it, but I just had a mini revelation. If your programming language supports closures (or code blocks, whatever) then you can create local closures that implement some kind of test to clean up your logical branching.

I had the situation recently where a particular bit of code was getting hard to follow. The problem was that I had if clauses that were getting unwieldy.

The following (rather contrived) example is written in groovy

if (((thing instanceof List) == false) || thing.size() > 0) {
    // do stuff
}

While that’s reasonably easy to understand, it could be better by naming the test …

def isnt_list_or_has_elements = {
    return ((it instanceof List) == false) || it.size() > 0
}

if (isnt_list_or_has_elements(thing)) {
    // do stuff
}

Probably not a new idea, but a handy one nonetheless.

Posted: Mar 3rd, 2008 @ 8:32 pm

Comments

Archive · RSS · Theme by Autumn