Maintainable HashCode and Equals Using Apache Commons

本文探讨了自动代码生成的hashCode和equals方法的使用,指出其可能导致的维护成本增加、代码覆盖率降低及美观性问题,并推荐使用Apache Commons库中的builders替代手动实现。

Java hashCode and equals methods can be tricky to implement correctly. Fortunately, all majors IDEs allow generating them. For example, this is how they look like for a class with two attributes when generated in Eclipse:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
@Override
public int hashCode() {
     final int prime = 31 ;
     int result = 1 ;
     result = prime * result + ((firstName == null ) ? 0 : firstName.hashCode());
     result = prime * result + ((lastName == null ) ? 0 : lastName.hashCode());
     return result;
}
 
@Override
public boolean equals(Object obj) {
     if ( this == obj)
         return true ;
     if (obj == null )
         return false ;
     if (getClass() != obj.getClass())
         return false ;
     Person other = (Person) obj;
     if (firstName == null ) {
         if (other.firstName != null )
             return false ;
     } else if (!firstName.equals(other.firstName))
         return false ;
     if (lastName == null ) {
         if (other.lastName != null )
             return false ;
     } else if (!lastName.equals(other.lastName))
          return false ;
     return true ;
}

It’s better than writing all this by hand but I still don’t like it. Here’s why:

  • It makes it way too easy to forget about updating them after adding a new field
  • It lowers the code coverage when not properly tested
  • It is just plain ugly

The first reason is the most important one. Having to remember about updating generated equals and hashCode methods when adding new fields increases the maintenance cost. Forgetting to do so may result in nasty bugs.

Because of that I never use generated hashCode and equals. I use builders from Apache Commons instead. In the most basic scenario they look like this:

1
2
3
4
5
6
7
8
9
@Override
public boolean equals(Object obj) {
     return EqualsBuilder.reflectionEquals( this , obj);
}
 
@Override
public int hashCode() {
     return HashCodeBuilder.reflectionHashCode( this );
}

They retrieve values using reflection from all fields except for transient and static ones. Most of the time this is precisely what I want. If you need some customizations check out the API documentation.

转载于:https://www.cnblogs.com/reynold-lei/p/3585726.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值