Equality operator for identityless classes
Kevin Bourrillion
kevinb at google.com
Wed Nov 3 18:23:37 UTC 2021
On Wed, Nov 3, 2021 at 11:05 AM Dan Smith <daniel.smith at oracle.com> wrote:
I'm not sure about this leap: while it's true that `==` is sometimes
> equivalent to `equals`, in general, you can't be sure without deep
> knowledge about the class. As a coding convention, seems reasonable to me
> to continue to expect clients to use `equals` rather than trying to develop
> a finer-grained distinction between different classes. I think it's
> perfectly fine advice for most code to continue to treat `==` as a smell,
> like they always have.
>
That is the "hygienic" line that we've been sorta-holding inside Google
with modest success. And I think it's the direction of gravity among static
analysis tools and really good style guides etc.
But it's a pretty hard line to hold as it stands, because the visceral
appeal of `==` is just too strong, and `!=` much stronger yet. I think it
would get near-impossible once there are a proliferation of user-defined
identityless classes where `==` "happens to be safe". We'd plead the case
that "sure, they're safe now, but this kind of unsafety is viral, so it's
fragile", yadda yadda, but who knows.
(One thing that has maybe helped us hold the line is that the most common
cases are enums, and we get to say "eh, `switch` is better anyway". So I
guess it's worth noting that at least other types supporting pattern
matching will have this same escape valve. That said, switch with only one
arm is a tough pill for people to swallow (I don't recall if `instanceof`
does or means to support *all* such cases or not).)
--
Kevin Bourrillion | Java Librarian | Google, Inc. | kevinb at google.com
More information about the valhalla-spec-observers
mailing list