Is Using Boolean Arithmetic Like This Ever a Good Idea?

0
0
Asked By MellowPine47 On

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?

4 Answers

Answered By ClearSkies_82 On

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.

Answered By PracticalOtter5 On

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.

Answered By HumanReadable_31 On

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.

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.

Answered By BranchlessBard6 On

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.

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.