Deprecate `!a == b`
Timon Gehr
timon.gehr at gmx.ch
Thu Aug 15 16:40:31 UTC 2024
On 8/13/24 22:30, IchorDev wrote:
> On Tuesday, 13 August 2024 at 10:14:29 UTC, Timon Gehr wrote:
>> A bug that crops up now and then in D is that someone negates `a == b`
>> by prepending a `!`. The result is `!a == b`. This parses as `(!a) ==
>> b` and will often silently do the wrong thing because negation implies
>> cast to `bool`, and `bool` can be compared with integral types and
>> `enum` members.
>>
>> I think it would be better for this to give a diagnostic and require
>> explicit parentheses, similar to bitwise operators (where the operator
>> precedence is unintuitive in the other direction).
>
> Doesn’t require a DIP, but I’ve also never seen anyone think this would
> work?
The main issue is this is a typo that indeed happens now and then, not
that people would think it works.
E.g., when you have:
`foo() || function_call_long_name() == c`
Now you negate the entire thing:
`!(foo() || function_call_long_name() == c)`
Now you think it would be more readable with individual negations.
!foo() && !function_call_long_name() == c`
This could easily happen, particularly if you are tired and you write a
lot of Python.
Now you compile and it does not work. If you test well enough, you'll
notice it. You debug for a few minutes and eventually come across this
part of the code again and notice the mistake. This could all be dealt
with a bit more efficiently.
> Do we really need to pander to people who don’t even understand
> that logical operators only *return* `bool`?
That's a strawman, and a bit insulting to anyone who has made this
particular typo.
> Maybe that seems harsh, but
> I have never even thought of doing this because it’s just so obviously
> wrong—if I wrote it then I must have meant what I wrote, and I was
> probably happy with how it looked too.
Your elitist attitude is somewhat common and I think used to make
similar (if somewhat less strong) statements 10 years ago, but I think
it was not particularly wise. In the end, most code you'll run is not
written by you. And most readers of your code do not want to read `!a==b`.
> Having to wrap it in parenthesis
> would just negate that and add to my code’s parenthesis hell.
>
> P.S. this isn’t a bug;
This is a DIP idea, not a bug report.
> and `!` is ‘logical not’, not ‘negation’.
Those are in fact synonyms.
https://en.wikipedia.org/wiki/Negation
More information about the dip.ideas
mailing list