Is Using Boolean Arithmetic Like This a Good Programming Practice?

0
0
Asked By MellowHarbor47 On

I wrote a line that chooses between different values based on whether `IorC` is equal to `"i"`, `"c"`, or `"s"`, using Boolean results as arithmetic or multiplication factors: `IorC = IorC**(IorC == "i") + CodedF**(IorC == "c") + ""*(IorC == "s")`. Here, `IorC` represents input, a hard-coded formula, or skipping the calculation. Is this a clever or efficient approach, or should I use a more conventional structure?

4 Answers

Answered By BranchlessBirch5 On

The only plausible justification would be a very specific performance requirement, such as deliberately avoiding branches. Even then, measure it first: a compiler may already optimize a readable conditional version, and this expression could introduce other problems or type conversions. Without profiling data, clarity is the better choice.

Answered By ClearPath8 On

This is technically possible in some languages, but it is much harder to understand than an `if`/`else` chain or a `switch` statement. Code should primarily be written for the people who will read and maintain it, not just for the computer. Most code reviews would reject this unless there were an unusually strong reason to use it.

Answered By QuietCactus91 On

Boolean expressions themselves are useful, especially when combined with Boolean operators. Treating their true and false results as numeric exponents or multipliers is a different matter and is generally poor style here. Also, this is an assignment or expression rather than an equation, since `=` usually assigns a value in programming languages.

Answered By NovaLime_26 On

A conditional structure would make the intent obvious: if the mode is input, do one thing; if it is the hard-coded formula, do another; and if it is skip, avoid the calculation. Once one condition matches, checking the other alternatives through arithmetic expressions is unnecessary and makes the logic look more complicated than it is.

MellowHarbor47 -

The three values were meant to represent input, a hard-coded calculation, and skipping the calculation.

NovaLime_26 -

That explanation is exactly why named cases or ordinary conditionals would help. The code should communicate those meanings without requiring someone to decode the expression first.

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.