0

I'm using Guava Objects.equal method. According to Guava API this Objects.equal method returns true if a and b are both null. I am not sure if I want this behavior on null fields for business key fields. So I think null!=null on fields participating in equals method. Each field is important to determine equality. I am also using Hibernate, so if I write equals like below, it looks just a bit unusual.

Do you see anything wrong with below equals method?

class Xyz
    ...............
    private Attr attr; //This is a business Key!
    private Attr2 attr2;// This is NOT a business key!

    @Override
    public boolean equals(Object obj)
    {
    return this == obj || (MyUtil.preEquals(this, obj) && xyzEquals(obj));
    }

    private boolean xyzEquals(Object obj)
    {
        final Xyz other = (Xyz) obj;

        // I want below check to make sure none of the business keys are NOT null
        if(getAttr()==null||other.getAttr()==null) return false;

        // I don't need below check since that attribute is not one of my business keys.
        // Still it participates in determining equality.
        // But it's not going to return false if either is null
        // if(getAttr2()==null||other.getAttr2()==null) return false;


        return Objects.equal(getAttr(), other.getAttr())
         && Objects.equal(getAttr2(), other.getAttr2());
    }
    ..............
    MyUtil class
    ..............
    public static boolean preEquals( Object thiz, Object obj )
    {
            if ( obj == null  || !thiz.getClass().isAssignableFrom(obj.getClass()))
            {
                return false;
            }
            return true;
        } 
Omar Hrynkiewicz
  • 502
  • 1
  • 8
  • 21
aug70co
  • 3,965
  • 5
  • 30
  • 44

0 Answers0