SyntaxHighlighter

Friday, July 8, 2011

Simpler if condition and Truthy/Falsy

Coming from Java land, I'm enjoying the ability to write shorter code in groovy than in Java. The condition inside an if statement is one of those. Given cool is a boolean, in Java I'd do this.
if (cool == true) {
// do something cool
} else {
// do something hot
}
In groovy, I can do this.
if (cool) {
// do something cool
} else {
// do something hot
}
But it's good to remember what actually gets counted as true or false. Although I don't like using null as a value, I had to deal with one the other day. I had a return value returned from a service call, the service call itself returned either a String or null.
def something = oldService.tellMeSomething()

if (something == null) {
// I don't like null, but I have to live with it for now.
} else {
// work on something
}
I got excited and changed the code to the following.
def something = oldService.tellMeSomething() // same service call
if (!something) {
// I don't like null, but I have to live with it for now.
} else {
// work on something
}
Then, I suddenly had a hunch that this might be wrong. The thing was that an empty String is a legitimate value returned, and I wasn't sure if an empty String would be evaluated as true or false. So I ran the following in a groovyConsole.
def e = ""
def n = null

if (e) {
println "empty string is truthy"
} else {
println "empty string is falsy"
}

// check for the opposite case too for a good measure.
if (!e) {
println '(!empty string) is truthy'
} else {
println "(!empty string) is falsy"
}

if (n) {
println "null is truthy"
} else {
println "null is falsy"
}


// check for the opposite case too for a good measure.
if (!n) {
println "(!null) is truthy"
} else {
println "(!null) is falsy"
}
If you ran that, or you know groovy better than I do, you might be relieved to know that I reverted my change back to the original (and I sighed a little too for the use of null).

No comments:

Post a Comment