Is Using Boolean Arithmetic Like This Ever a Good Idea?
Asked by
MellowPine47
I wrote a single line that chooses between different expressions based on whether `IorC` is equal to `"i"`, `"c"`, or `"s"`:
`IorC = IorC**(IorC == "i") + CodedF**(IorC == "c") + ""*(IorC == "s")`
Here, `i` means using input, `c` means using a hard-coded formula, and `s` means skipping the calculations. I was trying to use Boolean results as part of the expression instead of writing conditional statements. Is this a clever or useful technique, or would an `if`/`else` chain or `switch` statement be better?
Answers
Unless you have measured a very specific performance problem, there is no good reason to write it this way. Compilers can often optimize clear conditional code themselves, while this expression makes the logic obscure and may even evaluate parts you meant to skip.
Reply to this answer
Boolean expressions are useful when you are actually combining conditions with operations like AND, OR, or NOT. Treating Boolean values as numeric selectors is a separate trick, and it usually hurts readability. A named function or a `switch` would make the three cases much clearer.
Reply to this answer
The main issue is not whether the line is clever; it is whether another programmer can safely modify it later. This kind of compressed expression would be difficult to review and easy to break. Write the straightforward version first, then only consider a more unusual approach if profiling proves it is necessary.
Reply to this answer
This is technically possible in some languages, but it is much harder to understand than ordinary control flow. Use `if`/`else` or `switch` so the intent is immediately obvious to anyone reading or maintaining the code.
Reply to this answer
Add your answer
Answers are reviewed before publication.
TinyCloud9: Exactly. If the code needs an explanation before people can understand what `i`, `c`, and `s` mean, the structure probably needs clearer names and separate branches.