Wednesday, 7 August 2013

Lazy evaluation not working as it should

Lazy evaluation not working as it should

I had to evaluate a boolean expression frecuently, so I converted it in a
private method in it's class. Here is the code it's causing me trouble:
//"x", "y" and "team" are already defined
return (map.isWalkable(x,y) &&
(!map.isOccupied(x,y) || map.getOccupant(x, y)).getTeam() == team) );
Methods should be preety much self-explanatory as for the purpose of this
question. Now, isWalkable and isOccupied both return a boolean, and
getOccupant is the only method returning an object reference. The problem
is that I'm getting a NullPointerException when executing this piece of
code, and that shouldn't be happening because isOccupied returns true if
and only if map.getOccupant != null (that's actually what that method
returns). So with a language supporting lazy boolean evaluation from left
to right (as I assume java is, or at least that's what I was able to read)
the getOccupant method should never be executed whenever it would return
null am I right?
Is this more compiler-dependent than I thought it was? Should it be safer
if I used if statements, or is there simply something obvious I'm missing
here, maybe operations get resolved the other way round.

No comments:

Post a Comment