Comp Lang: Abuse of Logic Operators (Short-Circuit) as Control Flow
One of the most idiotic programing practice, is to use “or” operator as branch control. This is so in bash, python, JavaScript, emacs lisp.
For example:
mkdir x && cd x
x = y || 4;
y = None x = y or 3 print(x) # 3
(setq file-name (or load-file-name buffer-file-name))
using “or” for branch control, is a hack abusing a lang design problem of logical “or” and evaluation strategy.
a better name for the typical “or” semantics is
get_first_true
.
Problem of or-operator for Short-Circuit Evaluation
The problem of using “or” as flow control is that it is no longer a boolean logic operation.
For example, if “or” is used as boolean logic, then the compiler can do parallel evaluation on the clauses. But if you are using it as flow control, this cannot be done.
Also, this abuse of semantics forces a round-about way of reading code logic. For example,
x = y or 3
There is the boolean operator “or”. So, you read it as: x gets a boolean value, namely true or false.
But that is not what the code is actually meant to do.
rather, you must read it like this:
x gets the value of, if y evaluates to a value that is considered true, namely, it is not undefined, then, that, else, 3.
Here is what Edsger W Dijkstra has to say about the problem, from a different perspective:
The conditional connectives — “cand” and “cor” for short — are … less innocent than they might seem at first sight. For instance, cor does not distribute over cand: compare
(A cand B) cor C with (A cor C) cand (B cor C);
in the case ¬A ∧ C , the second expression requires B to be defined, the first one does not. Because the conditional connectives thus complicate the formal reasoning about programs, they are better avoided.
— Edsger W. Dijkstra
Programing Idioms and Style
Programing Language Design
- Ontology of Programing Languages
- Comp Lang: Why I Hate Exceptions
- Comp Lang: Iterator, Enumerator, Abstraction Went Wrong (2016)
- Comp Lang: Should Array Index Start at 0 or 1?
- Comp Lang: Where does the “main” function in programing languages came from?
- Comp Lang: is the Map Function Functional Programing in Syntax or Semantics
- Comp Lang: Should Map Function Specify Order
- Comp Lang: Abuse of Logic Operators (Short-Circuit) as Control Flow
- Comp Lang: Bit Operators Idiocy
- Comp Lang: Hack of Bitmask as Boolean Parameters
- Comp Lang: Function Dependency
- The Complexity of Java Access Specifiers
- Comp Lang: C Cpp Java Coders Don't Know Scientific Programing Languages