Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it a bad practice to include non-public fields into equals() [closed]

Tags:

java

Is it a bad practice to include fields inaccessible by any public methods (and which themselves are not and can not be derived from any other public fields) into equals() ?

What are possible bad consequences of doing so?

Is this described as a bad practice somewhere? (I assume hash/equals contract is ok)

I feel, such equals would be philosophically very wrong. Such equals is not observed in the world. But can it lead to real programming misbehavior, philosophy aside?

like image 767
Alexander Kulyakhtin Avatar asked Jul 31 '14 15:07

Alexander Kulyakhtin


Video Answer


1 Answers

It's absolutely fine and sometimes necessary. The only fields that you shouldn't compare are ones marked as transient.

I'd assert that two instances are equal if and only if their serialisations are equal. That's why transient matters and the degree of field encapsulation doesn't.

like image 162
Bathsheba Avatar answered Oct 05 '22 22:10

Bathsheba