DEV Community

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

Collapse
 
neilmadden profile image
Neil Madden

My favourite approach is to implement Comparable<T> then make equals just do:

public boolean equals(Object that) {
    return this == that
        || that instanceof T && this.compareTo((T) that) == 0;
}

Isn't always applicable but ensures compareTo is consistent with equals when you want to implement both anyway. Otherwise I write an isEqualTo(T that) method and do similar.

Collapse
 
voins profile image
Alexey Voinov

Yeah, I tried to implement isEqualTo(), but I end up with a bunch of nice short methods, that do not belong to my class, and that doesn't look nice. Where should I put it? It would be nice to have some mixin, but I cannot override equals() there, and in that case there will be equals() that calls some methods that I do not see, and by some magic, it later calls isEqualTo().

I like idea with Comparable. It makes sense, but in some situations it is an overkill, I agree.