Why && is no replacement for ?: or if

I've one particularly ugly example of C++ code where a fellow programmer used something like pre_condition && check_func(params) to prevent the function from beeing executed only if the pre_condition was successful. Well, since it's standard behaviour, I can't argue about it operating properly when doing so. But, and that's the point of this post, I find it bad style to use as a replacement for normal conditions. First of all, && is thought for series of logical checks. To reduce the number of checks to be done, it doesn't continue if the first operand is null - good idea! However, it's limited to expressions evaluating in either true or false - you can't use it like ?: after all and it's no good idea to use it for conditions on a regular base. It's also often ambigious what the programmer thought when using it - did he want the side effect of execution or just to final value? Do the associated expressions contain operations or function calls that shouldn't be called? You can't always decipher what it's meant to be and using ?:, if or switch is always a better way of clearly stating WHAT it is.

I have to admit that it's tempting to use the operator for quick checks. But honestly, I found it way harder to distinguish complex formulas when && is used for actual conditions. ?: is very clean way to tell you stuff - use it wisely!

Edit: Also, ever though about what might happen if you put this stuff into an assertion you can't catch during debug mode? Right, you'll never know what operand evaluated to false. Another reason not use it this way.

No comments: