Tuesday, October 23, 2012

@GeneratedCode: Document when code was auto-generated

IDEs such as IntelliJ and Eclipse provide functionality to generate methods including toString(), equals() and hashCode().

When making changes to existing code, and I need to update such possibly auto-generated methods, I often wonder whether I can just drop and re-create them, or if they include some magic I'm not aware of.

A very simple example class in Java with equals and hashCode:

public class Person {

    private final String givenName;
    private final String surname;
    private final org.joda.time.LocalDate dateOfBirth;

    public Person(String givenName, String surname, LocalDate dateOfBirth) {
        this.givenName = givenName;
        this.surname = surname;
        this.dateOfBirth = dateOfBirth;
    }
 
    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        Person person = (Person) o;

        if (dateOfBirth != null ? !dateOfBirth.equals(person.dateOfBirth) : person.dateOfBirth != null) return false;
        if (givenName != null ? !givenName.equals(person.givenName) : person.givenName != null) return false;
        if (surname != null ? !surname.equals(person.surname) : person.surname != null) return false;

        return true;
    }

    @Override
    public int hashCode() {
        int result = givenName != null ? givenName.hashCode() : 0;
        result = 31 * result + (surname != null ? surname.hashCode() : 0);
        result = 31 * result + (dateOfBirth != null ? dateOfBirth.hashCode() : 0);
        return result;
    }

}

Scenario: add another field called gender. Even though the class really is very basic, it already takes a moment to understand. Should I hack in the additional field, or re-create the methods from scratch?

With more complex classes it gets worse.

My solution: I document whenever I have the IDE create such code for me. I've chosen a new @GeneratedCode annotation. A Javadoc comment would work too. Once I modify the code by hand I remove the annotation.

A suggestion for IDE developers: The generated code could include an annotation, Javadoc or other visual mark. And, even better, it could remove that automatically when the code gets modified by the programmer and differs from the original generated one. And (more wishful thinking) when refactoring the class (adding a new field) it could even ask if that new field should be included in the method, which could simply be done be re-creating.

No comments:

Post a Comment

Post a Comment