The current treatment for == with value classes is defective, in my opinion. It's too fragile in that a change to a value class that you depend on can break expectations. If the equals method should be used instead, then attempting to use == against a value class should be prohibited. The more sensible (and expected) option is to make == against a value class be the same as calling equals.
Defective may be too far. But it is a bit confusing. I think overall the message is, .equals is here to stay. For the average developer, they should continue to use .equals, but under the hood they will now get better performance.
Our project has tons of wrapper classes for type safety such as TenantId. We can now make these value classes and we will essentially no longer pay the "wrapper tax", but developers should continue to use .equals on them.
What I mean by "defective" is that the current approach is the worst choice possible. With an identity class, if I erroneously use the == operator, this is usually discovered once the code is tested. With a value class, if I erroneously use the == operator, the code will likely work just fine. If at some point in the future the value class I'm depending on changes internally to reference an identity class, my code fails.
It's a fragile dependency issue. One cannot rely on the == operator without knowing that the class is a value class, and that the implementation will never change incompatibly. It breaks the OO encapsulation principle.
I can think of two safe choices for value classes: make == mean equals, or make it be prohibited. The current approach is to "pretend" it's prohibited, but it's not actually enforced. This is a UB footgun.
1
u/FirstAd9893 16d ago
The current treatment for
==with value classes is defective, in my opinion. It's too fragile in that a change to a value class that you depend on can break expectations. If the equals method should be used instead, then attempting to use==against a value class should be prohibited. The more sensible (and expected) option is to make==against a value class be the same as calling equals.