4 ms·
As a simple example, `x.equals(y)` accepts an arbitrary Object y. This one example has ramifications all over the place, e.g. I had a bug recently where I was c
by chriswarbo 6y ago
As a simple example, `x.equals(y)` accepts an arbitrary Object y. This one example has ramifications all over the place, e.g. I had a bug recently where I was checking if an element was in a collection, using `x.contains(y)`. That .contains method seems to use .equals, since it allows y to be any Object. In my case x was a collection of MyType values whilst y was a MyWrapper<MyType> which I forgot to unwrap. Rather than giving a type error, this check was always returning false.
Since then I've defined a .has method which requires the argument to have the same type as the collection, which completely avoids such problems.
- twic 6y agoExcellent example, thank you.
- sixbrx 6y agoYes and also Map's "get(Object key)" and "remove(Object key)". Those are the bane of refactorings, for me.
- blandflakes 6y agoFun fact, this also happens in Scala - try to List.contains an object from a type different than that stored in the list. Compiles, returns false always.
- chriswarbo 6y agoI actually encountered this in Scala (my example originally had [square brackets] rather than <pointy ones>). My `.has` method uses cats.Eq and is monkey-patched on to the Iterable interface: implicit final class IOps[A: cats.Eq](val i: Iterable[A]) { def has(x: A): Boolean = i.exists(_.eqv(x)) }
- blandflakes 6y agoHa, yup. We use the .contains_ method with cats eq on the objects, but this is clever.
- oftenwrong 6y agoThose are ancient warts that can never be changed. Almost any static analysis suite will warn you about using equals and contains with incorrect types.
- chriswarbo 6y ago> Almost any static analysis suite Yet not the most important static analysis suite, which is included in the compiler, and enforced on all code: the type checker ;)
- kaba0 6y agoAlt insert generate equals method, select fields, ready. Or use a record. It is such a minuscule part of the language, that it simply doesn’t matter compared to every other line of code, lib, ecosystem. You may imagine how much more productive you are that this language has sane equals, but it is not even a reasonable constant factor.
- chriswarbo 6y ago> Alt insert generate equals method, select fields, ready. This sounds like you're not programming in the Java language, you're programming in some sort of graphical macro language which compiles down to Java (presumably built-in to an IDE of some sort?). The fact that people resort to such things is evidence that this is a valid criticism of the Java language.
- kaba0 6y agoFor data only classes, records are an existing solution. For non-data classes you have to specify what equals means. Is two database connections to the same db equals? No, even though they may have the exact same fields.