有什么方法可以使hashCode/equals与类的业务定义保持一致? [英] What are ways to keep hashCode/equals consistent with the business definition of the class?

查看:69
本文介绍了有什么方法可以使hashCode/equals与类的业务定义保持一致?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对象javadocs和Josh Bloch向我们介绍了如何实现hashCode/equals,并且好的IDE可以正确处理各种类型的字段. 此处对此进行了一些讨论.

Object javadocs and Josh Bloch tell us a great deal about how hashCode/equals should be implemented, and good IDEs will handle fields of various types correctly. Some discussion about all that is here.

这个问题是关于下一步的:您如何确保它们保持良好?

This question is about the next step: How do you make sure that they remain good?

尤其是,我觉得对于大多数类,应该按照Bloch的建议(以及Eclipse和其他IDE的实现)来实现equals/hashCode,并考虑该类上所有非派生的业务逻辑字段.在将新字段添加到类中作为持续工作的一部分时,人们常常忘记将它们添加到equals/hashCode实现中.当两个对象看上去相等,但实际上由于最近引入的字段的值不同时,这可能会导致难以发现的错误.

In particular, I feel that for most Classes, equals/hashCode should be implemented as Bloch suggests (and Eclipse and other IDE's implement), and take in to account all non-derived, business-logic, fields on that class. While adding new fields to a class as part of continuing work, people often forget to add them to the equals/hashCode implementation. This can lead to hard-to-find bugs, when two objects appear equal, but in fact differ by the value of a recently introduced field.

随着成员字段的更改,团队(甚至一个!)如何帮助确保类上的equals/hashCode继续考虑所有相关字段?

How can a team (even of one!) help ensure that the equals/hashCode on a class continue to take in to account all relevant fields, as the member fields change?

我知道Apache的EqualsBuilder和HashCodeBuilder可以使用反射,这显然会考虑正确的字段,但是我想避免使用它们的性能成本.还有其他方法可以标记不包含在equals/hashCode中的字段吗?静态代码分析,IDE功能,单元测试技术?

I know that Apache's EqualsBuilder and HashCodeBuilder can use reflection, which obviously would take in to account the correct fields, but I want to avoid the performance costs of using them. Are there other approaches to flag up fields that are not included in equals/hashCode, and should be? Static code analysis, IDE features, unit test techniques?

推荐答案

我还没有研究过 Project龙目岛,但是我立即想到,hmm注释可以与代码一起使用发电机.

I haven't looked into Project Lombok much, but I immediately thought, hmm annotations would work with a code generator.

这篇关于有什么方法可以使hashCode/equals与类的业务定义保持一致?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆