Search code examples
javajpaormumlclass-diagram

Inheritance strategy


I know that is more than one strategy to handle with inheritance in java, and that best performance is achieved with single table.

The schema below is a class diagram: enter image description here

Sorry the schema is french. Without going int the details, "personne" means person, "employeur" employer, "proprietaire" landlord, "locataire" tenant, and "Conge" holidays.

How can I derive from this schema which best inheritance strategy that I should use ?


Solution

  • Are you sure ?

    Before answering your specific question, may I criticize your inheritance logic ?

    Your base class Person is derived into Landlord , Tenant and Employer . Unfortunately, a Person could in reality have several (or even all) roles in the same time (e.g. renting his flat, and being employer).

    Of course, it's your right to model the domain like this, and to work with several objects that have identical Person data with a different id. But this doesn't reflect the real world so well. So if a Landlord would change its address, you'd need to check if some Employer or Tenant correspond to the same person, to updated them too.

    Quote of the day: In case of doubt, prefer composition over inheritance

    Best strategy for your model

    Here are the possible strategies:

    • single table: all the properties of all the inherited classes are merged together in a single big table. This works best if only a couple of additional properties are defined for each derived class. Unfortunately, Employer has an association, and Landlord has a hidden (self referencing) association with List<Landlord>. With different relations for the different children, this model could have some drawbacks.
    • table per (concrete) class: all the properties of the parent class are merged into the child classes. In this case, you'll end up with a unique Person.id that has to remain unique across the three tables.
    • join: every class has its own table, and appropriate joins put the pieces together. This can cope with all your requirements here and give you the best flexibility to evolve and get more complex children.

    So the Join would be the strategy i'd recomend.

    Alternative class models

    Coming back to my observation that Tenant, Landlord and Employer are roles of a Person, I'd model this differently: no inheritance, but a Person would have a 0 to many (0..*) relationship with Tenant, Landlord, and Employer.

    In this case a person could exist in my system without any active role. I could link it to whatever role is relevant at any given time, and if there's a change of address, I'd need only to change one person with its unique id. Wouldn't this be a model much closer to the reality of the domain ?