DEV Community

Discussion on: Did you ever try to write Java equals() with clean code style?

 
pnambic profile image
Daniel Schmitt

I guess I just fail to see what problems either of our equals() implementations have with regards to Uncle Bob's cleanliness standards. It doesn't get more concise than that, and basically by definition equals() does exactly one thing. It's pure, and it concerns itself with one level of abstraction (the one the object is on). So I - wrongly - assumed that it would be a design question.

On that note, I realise that there's a difference between value types and entity types; what I was getting at is that if your equals()method is becoming unwieldy, you're likely either dealing with a massively complicated value type (and I have honestly never seen such a thing), or an entity that could benefit from a more explicit approach to identity. If I'm wrong on both counts, I'm all the more curious about what is actually going on in your specific case.

Thread Thread
 
voins profile image
Alexey Voinov

Let me put it like this. Do you remember, that clean code should be readable (almost) like plain English? If I start to read your version, for example, it will be something like "if rhs is instance of NeedEquals and this is the same as rhs or primitive is the same as field primitive in rhs cast to NeedEquals ..." I feel like this is just too low level, and part with Object.equals(...) is hardly readable (in that style) at all.

What I would love to read is something like "if this is the same instance as that or if that is of the same class as this and every field of this is equal to corresponding field of that", or even "this is the same instance as that or has the same content". Do you see it?

There some problems with this approach though, mainly IDE warnings, which could be ignored, but again, it reduces readability and most of the time requires comments, and placement of those methods, because they are very generic and not specific to my class, except for fields comparison.

BTW, thank you for helping me expressing all of this explicitly. :) I love to find things that are obvious to me and not so obvious to someone else.

Thread Thread
 
pnambic profile image
Daniel Schmitt • Edited

The only thing I know that comes close to what I think you are looking for has been mentioned already: EqualsBuilder from Apache Commons. Or you could go for a reflection-based approach like in Unitils, but this is probably unacceptable performance-wise outside of unit tests.

Funnily enough, I read both your code and my code exactly like you say you'd want it to read, but I agree that it's not "in the code" as such. It's an idiom - OK, an equals() method, now then: the questions I need the code to answer are: which fields?, shallow or deep comparisons?, nulls OK?, subclasses OK? Both implementations give me those answers at a glance. This can bite you in code reviews, but otherwise it helps to not overthink things. ;)