Eradicate boilerplate

Viewed 71
public class Toponym {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    public int id;

    @Column(columnDefinition="TEXT default ''", nullable = false)
    public String name;
}


public class LevelOneEntity {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    public int id;


    @Column(columnDefinition = "boolean default false", nullable = false)
    private boolean archived;
}



public class LevelTwoEntity {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    public int id;

    @Column(columnDefinition = "boolean default false", nullable = false)
    private boolean archived;
}

These two classes definitely have some boilerplate code. If multiple inheritance were a reality, I'd organize two mixins here: IdMixin and ArchivedMixin. Therefore classes would contain no bodies at all. But in Java it is not possible.

It may be possible to use multiple interfaces but they can't contain the code itself if I'm not mistaken.

How to cope with such a problem in Java?

1 Answers

If those annotations are allowed on methods, not only on fields (e.g. getters or setters), you can declare them in interfaces and implement as many interfaces as you want. The fields will still be declared in each derived class, though, but you won't need to restate the annotations for them.

Otherwise, you'll have to create a class hierarchy that allows for the flexibility you need:

class Entity // contains annotated ID field and declares the generic ID type
class ArchivedEntity extends Entity // if you don't expect to have non-entity archived classes (i.e. archived objects with no ID)
... etc

This can get pretty complex as you add more combinations.

Related