views:

39

answers:

1

Canonical example:

while foo.hasBar() && foo.getBar() != spam
{
     do lots of stuff
}

foo.getBar() will raise an exception if it has no bar. However, it is guaranteed that this expression will not be evaluated unless foo has a bar. Is that considered a good programming style?

+2  A: 

If you're working in a language that guarantees that kind of evaluation for a boolean and (this is very common, and is called short-circuit evaluation), then yes, that's of course fine to rely on.

On the other hand, needlessly repeating the foo.hasBar() test in the loop seems very clumsy to me.

unwind