DEV Community

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

 
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. ;)