I was working on a piece of code when I noticed that an if
statement could work or crash depending on the order used for the parts connected with and
.
You can replicate the problem like this:
boolean func(String x) {
assert x
return true
}
v = "text"
if (v != "" && func(v)) {
println("Hello")
}
Depending on whether v != ""
or func(v)
is used first, the if
causes an assertion error or not.
This is because groovy checks the first expression and if that one is already false it does not even evaluate the second as the and operator will always cause the expression to be false.
So in groovy the connected condition are combined like this:
if (v != "") {
if (func(v)) {
*[...]*
}
}
I know that at least some other languages have a similar behavior (I believe in Java you can switch it by using &
or &&
) but I ask myself is this really the way to go. It seems quite unintuitive to understand and I don't think it conveys the importance of the order in this statement.
How can I make it clear on a code basis that the order is important and should be considered when altering code around it? Or should I just forget about it and assume that people check for something like that?
Upon doing further research I discovered an entry on the basic groovy documentation site for operators: Groovy - Short Circuiting
The general term seems to describe this seems to be 'short-circuit evaluation'. Very appropriate. I adapted the title of the question as I wanted to put it in there but didn't know the terminology.