Search code examples
logicprogramming-languageslanguage-design

Why don't programming languages use simplified boolean expressions?


I've never understood why we use syntax like this:

if (a == b || a == c)

when it could be simplified to something like this:

if (a == b || c)

Is this an issue with compilers or something? Can we really not account for a string of code like this and make it work?


Solution

  • There is no technical limitation that would make it impossible (or even too difficult) to implement a language that treats a == b || c as a shortcut for a == b || a == c. The problem is that it would be almost (?) impossible to come up with rules to do so only in the cases where that's what's expected.

    For instance consider the expression result == null || fileIsClosed where fileIsClosed is a boolean. Surely the programmer would not expect this to be treated as result == null || result == fileIsClosed. You could come up with additional rules like "the replacement is only applied if the right operand of || is not a boolean", but then the replacement also does not work if you do booleanResult == possibleResult1 || possibleResult2. In fact the only thing about this example, that tells us whether the programmer intended for the replacement to happen, are the names of the variables. Obviously the compiler can't infer meaning from variable names, so it'd be impossible to do what the user wants in every case, making simple rules without exceptions (like "expr1 || expr2 is true iff at least one of expr1 and expr2 are true") preferable.

    So in summary: We don't want the replacement to take place in all cases and inferring in which cases the replacements would make sense with complete accuracy would be impossible. Since it should be easy to reason about code, implementing a system that may or may not apply the replacement based on rules that 90% of programmers won't know or understand will lead to confusing behavior in certain cases and is therefore not a good idea.