You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
If I add a new field to a class, I can remember to update equals() but forget to update hashCode(). How would we detect this? In many cases, both methods should read all fields of a class, but that's probably too strong a check. (For example, a List.equals() implementation might read no fields directly, preferring to operation on the public size() and get() methods.) A weaker but probably still useful check is that the two methods read the same set of fields. False positives are still possible. For example, the check would flag a field containing a cached hash code, which would likely be read in hashCode() but not equals(). This particular example is avoidable by requiring the hashCode() looks at a subset of the fields that equals() looks at. I conjecture that it's more common for programmers to update equals() but forget to update hashCode() than vice versa, so this further weakened check would likely still catch most problems.
The text was updated successfully, but these errors were encountered:
This sounds worthwhile. Checking both methods in a class wouldn't be difficult. We may need to exempt classes that only implement one, unless #157 is implemented.
This will have plenty of false negatives for classes which compare fields via complex getters, but should work fairly well for simple data classes.
Fixes#35
RELNOTES: [InconsistentHashCode] Add a check to flag inconsistent implementations of hashCode.
-------------
Created by MOE: https://github.com/google/moe
MOE_MIGRATED_REVID=211950941
Original issue created by cpovirk@google.com on 2012-08-06 at 08:48 PM
If I add a new field to a class, I can remember to update equals() but forget to update hashCode(). How would we detect this? In many cases, both methods should read all fields of a class, but that's probably too strong a check. (For example, a List.equals() implementation might read no fields directly, preferring to operation on the public size() and get() methods.) A weaker but probably still useful check is that the two methods read the same set of fields. False positives are still possible. For example, the check would flag a field containing a cached hash code, which would likely be read in hashCode() but not equals(). This particular example is avoidable by requiring the hashCode() looks at a subset of the fields that equals() looks at. I conjecture that it's more common for programmers to update equals() but forget to update hashCode() than vice versa, so this further weakened check would likely still catch most problems.
The text was updated successfully, but these errors were encountered: