I am updating a Java project and had to add an equals() implementation 3 java DTO files (call them Child1, Child2 and Child3) which all extend the DTO Parent class. IntelliJ generated the following implentation.
@Override
public final boolean equals(Object o) {
if (this == o) return true;
if (o == null) return false;
Class<?> oEffectiveClass = o instanceof HibernateProxy ? ((HibernateProxy) o).getHibernateLazyInitializer().getPersistentClass() : o.getClass();
Class<?> thisEffectiveClass = this instanceof HibernateProxy ? ((HibernateProxy) this).getHibernateLazyInitializer().getPersistentClass() : this.getClass();
if (thisEffectiveClass != oEffectiveClass) return false;
Child1 that = (Child1) o;
return getId() != null && Objects.equals(getId(), that.getId());
}
My issue is I am getting dinged by sonarcube for duplicate code because the line
Child1 that = (Child1) o;
is the only line that is different between the three implementations. I tried putting this in Parent
protected Boolean baseEquals(Object o, Long id, Long thatId ) {
if (this == o) return true;
if (o == null) return false;
Class<?> oEffectiveClass = o instanceof HibernateProxy ? ((HibernateProxy) o).getHibernateLazyInitializer().getPersistentClass() : o.getClass();
Class<?> thisEffectiveClass = this instanceof HibernateProxy ? ((HibernateProxy) this).getHibernateLazyInitializer().getPersistentClass() : this.getClass();
if (thisEffectiveClass != oEffectiveClass) return false;
return id != null && Objects.equals(id, thatId);
}
and calling it with this.
@Override
public final boolean equals(Object o) {
if (this.getClass() != o.getClass()) return false;
Child1 that = (Child1) o;
return baseEquals(o, getId(), that.getId());
}
Is there a cleaner way to do it? Will the this.getClass() != o.getClass()
test prevent a ClassCastException or do I need the thisEffectiveClass != oEffectiveClass
test before I do the casting. I haven’t used Hibernate
enough to understand exactly what the second test does.