0

Say I have an Object that has 10 different fields. So what is the real different between these two implementations?

Using Apache EqualsBuilder

return new EqualsBuilder()
    .append(field1, o.getField1())
    .append(field2, o.getField2())
    ....
    .isEquals();

Using Home built

return field1.equals(o.getField1())
    && field2.equals(o.getField2())
    ....;

Both implementations I have to main new additional fields or remove field when they are refactored. So I am not sure why people think EqualsBuilder is a good implementation?

Churk
  • 4,556
  • 5
  • 22
  • 37
  • What happens when one of your operands is null? – Gabe Feb 16 '15 at 04:10
  • 1
    Not, it is not a duplicate because I am asking what is he difference, meaning I am asking performance and design best practice. So far from reading that post, I only get the feel that everything home grown is bad and using the framework is good without any actual reason. – Churk Feb 16 '15 at 04:12
  • @Gabe that would be something I encapsulate and make sure that is something I would check. Look at my comment to Elliott Frisch's Answer. – Churk Feb 16 '15 at 04:18

2 Answers2

0

The EqualsBuilder Javadoc says (in part with emphasis added),

This class provides methods to build a good equals method for any class. It follows rules laid out in Effective Java, by Joshua Bloch. In particular the rule for comparing doubles, floats, and arrays can be tricky. Also, making sure that equals() and hashCode() are consistent can be difficult.

Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
  • What I found equalsBuild to be most troublesome is the lack of ability to expand on the comparison. For example. What if I need the string comparison to render an equal if one field is blank and the comparing object has a null. – Churk Feb 16 '15 at 04:14
  • example: `return StringUtils.isNotBlank(a) && StringUtils.isNotBlank(b) ? StringUtils.equals(a, b) : StringUtils.isBlank(a.trim()) && StringUtils.isBlank(b.trim());` – Churk Feb 16 '15 at 04:16
  • @Churk When building your search method I would transform a null to a blank... or use a pattern matcher instead. – Elliott Frisch Feb 16 '15 at 04:21
0

field1.equals(o.getField1()) is good only for Object fields, it wont work for primitives

Anptk
  • 1,125
  • 2
  • 17
  • 28
Evgeniy Dorofeev
  • 133,369
  • 30
  • 199
  • 275