Avoid Circular Dependency

前端 未结 2 1509
野的像风
野的像风 2021-02-09 17:35

I am developing a travel management application. The design in question is something like following :

Each person in a tour is designated as a Traveler. Each Traveler ha

相关标签:
2条回答
  • 2021-02-09 18:27

    I would only have two tables in the database.

    Traveller and Password

    Traveller will have a Parent_Id field which will link back to the Traveller table and will store who the Main/Head traveller is. Also store fields common to either Main/Sub member in this table like contact number

    Then using inheritance and ORM create two different classes in your actual application. MainMember and SubMember MainMember would be all rows in Traveller where Parent_Id is null SubMember would be all rows in Traveller where Parent_Id is not null

    0 讨论(0)
  • 2021-02-09 18:29

    As you can see, the three tables - Traveler, MainMember and SubMember - have formed a circular dependency.

    No, this is not a circular dependency - no "node" in this graph can reach itself by following graph "edges" in their proper direction1. It would be more accurately described as "merged" or even (proto) "diamond-shaped" dependency.

    And no, it will not hurt your application.2

    You are effectively implementing inheritance (aka category, subclassing, subtyping, generalization hierarchy etc.), using "each class in separate table" approach. This approach is clean, but cannot guarantee presence3 and exclusivity4 out of box. There are ways to amend it so it does, and there are other implementation strategies for inheritance that can, but they have their own pros and cons.

    In my opinion, your model is just fine for what you are trying to accomplish and enforcing the presence/exclusivity at the application level is probably lesser evil than suffering the cons of trying to enforce it at the database level.


    1 "Direction" is from referencing to referenced table. Traveller doesn't reference MainMember nor SubMember and therefore breaks the cycle.

    2 Unless you are on a DBMS (such as MS SQL Server) that doesn't support referential actions on such "merged" dependencies (in which case you'd need to implement ON CASCADE DELETE through triggers).

    3 Traveller cannot exist alone (cannot be "abstract"), it must be MainMember or SubMember.

    4 Traveller cannot be both MainMember and SubMember.

    0 讨论(0)
提交回复
热议问题