Tuesday, April 27, 2010

Groovy Gotcha: optional return from an if block

Groovy 1.6 added optional return from if/else conditions. The optional return helps reduce code clutter, especially in closure blocks. But if you take advantage of the optional return, be sure your if condition also has an else block. Without the else, you'll be returning null when your if expression evaluates to false.

Look at the following example:

String computeUrl(boolean secure) {
 String url = "http://www.google.com"
 if (secure) {
  url = url.replace("http:", "https:")
 }
}

assert computeUrl(true)  == "https://www.google.com"
assert computeUrl(false) == null

If we add an else block, we get the desired behavior:

String computeUrl(boolean secure) {
 String url = "http://www.google.com"
 if (secure) {
  url = url.replace("http:", "https:")
 }
 else {
     url
 }
}

assert computeUrl(true)  == "https://www.google.com"
assert computeUrl(false) == "http://www.google.com"