Why are there no short-circuiting compound assignment operators `&&=` and `||=`?
some-java-user-99206970363698485155 at vodafonemail.de
some-java-user-99206970363698485155 at vodafonemail.de
Fri Aug 7 15:22:45 UTC 2020
Nearly all binary operators have a corresponding compound assignment operator. However, `&&` and `||`
don't have a compound assignment operator so people often use `&=` or `|=` instead. These operators
are not "short-circuiting", i.e. even if the right side has no effect on the assignment result it is
evaluated nonetheless. The problem is that often the right side of the assignment is side-effect free
and therefore calling it in these cases is inefficient, especially when its evaluation is expensive.
Additionally these assignments are commonly used inside of loops which increases the inefficiency
even further.
It is possible to get the same behavior `&&=` and `||=` would provide:
```
boolean b = ...
// b &&= testSomething()
if (b) {
b = testSomething();
}
// b ||= testSomething()
if (!b) {
b = testSomething();
}
```
Though, these alternatives are slightly more verbose and add a level of indentation (unless you write
the `if` statement in one line, which is however often discouraged).
https://stackoverflow.com/q/2324549/ shows that there is interest in having these operators and there
are no clear arguments why they don't exist yet.
The question is therefore: Has the JDK team discussed adding these operators in the past and if so
what where the reasons against adding them?
More information about the discuss
mailing list