Search code examples
javaannotationstostringlombok

Annotation or implementation for toString(), equals() and hashCode() methods?


I have seen the following implementation in a repository and I am confused:

@Entity
@Getter
@Setter
@ToString(callSuper = true)
@NoArgsConstructor
public class Employee extends BaseEntity {

    // properties

    @Override
    public int hashCode() {
        return super.hashCode();
    }

    @Override
    public boolean equals(Object other) {
        return super.equals(other);
    }
}

My questions are:

  1. Is it logical to implement these methods as they are already implemented in the base class? Is it unnecessary to implement hashCode(), equals() methods here and adding @ToString(callSuper = true) to the beginning of the entity class?

  2. For adding these methods in the entity, is it better to use annotation instead of adding 3-4 lines code for each method?

  3. I think there is a misuse regarding to these methods. Because 2 of them are implemented and one of them (toString) is added via annotation. I think all of them should be used in the same manner (all of them via annotation or all of them via implementation). Am I wrong?


Solution

    1. Yes, you should implement them also in the child classes. The reason is that you have additional properties on them that should be taken into account on both hashCode() and equals().
    2. That is a matter of personal opinion. Some people like to have full control over the code, some are happy to write less code and rely on dependencies such as lombok. I would use the annotations. If you need something more complex, then you can always write the methods yourself.
    3. If you have the annotation you shouldn't have the method implemented or your own, unless you want to avoid the annotation to do his job. Generally speaking, if you are ok with the annotations, you should stick to that. The important thing is to be consistent so that code is readable.