I don’t like short-circuiting. Here’s why:
It is a hack. i.e. It is (ab)using an implementation detail of
||, namely using the fact that the second operand is only evaluated if necessary to provide one-liner
if pred or
if !pred statements.
While I do experience a moment of childlike glee whenever I do something ‘clever’, I don’t consider it responsible language design. I teach maths students to prefer elegance over cleverness.
Consider C++ template metaprogramming. An entire meta-language has arisen from SFINAE – exploiting the fact that Substitution Failure Is Not An Error. It’s incredibly clever. People have got carried away doing absurdly complex operations by exploiting this behaviour. But it is insanely difficult to work with – leading to the poorest productivity I have ever witnessed. Nobody would design this syntax in retrospect.
Ok so I’m using a level 10 awfulness to illustrate a level 1 awfulness. But the point is the same.
My argument is this: short-circuiting creates an extra thing for the new user to have to figure out via RTFM. Also what is written on the page is conceptually far from what is going on so the user has to build brain machinery to handle this. Each time the encounter
pred && statement they have to say to themselves ‘if pred, do statement’.
What if we provided the following syntax:
pred then statement pred else statement
Anyone will be able to see that and instantly understand it and apply it elsewhere. No RTFM is necessary. No extra building of machinery is necessary. It is an effortless brain-scan/parse.
(EDIT: JB has shot a hole through using
Another syntax idea would be extending the ternary operator to make either branch optional:
pred ? stA : stB pred ? stA pred ? : stB
While this might require looking up the
? operator, it is still a pleasant scan/parse.
It has been suggested to use
pred : stB for the third option, but that currently parses as a
range. One solution would be to change the syntax for a range to
a..b a la Swift. I would be very much in favour of this as again it maps onto an existing concept: we all understand “a = 1…10” as pseudocode. Also it avoids clashing with Python’s
S[a:b] slicing syntax which actually selects elements
I’m writing this in the aftermath of the oh-so-painful RFC: Make
or aliases for
||. #19788 thread. I think it would be a pity to launch a new language that has
& bitwise and
&& sometimes used as straightforward logical and other times in short-circuiting.
I really like the idea of a language that facilitates picking up the syntax just by looking at it.