Should domain entities hold foreign keys or the related objects themselves?

934 views
Skip to first unread message

Jordan Walker

unread,
Nov 12, 2019, 10:05:46 AM11/12/19
to Clean Code Discussion
Should a Post entity have a user_id property which corresponds to the primary key (id) of a User entity, or should it instead have an author property which holds a reference to the actual User entity itself?

It seems that using foreign keys is leaking database-related concerns into the domain. Even using ids seem to be leaking database primary keys into the domain, and yet in Uncle Bob's case study all the entities have methods for getting/setting an id.

If entities should hold direct references to related entities (as opposed to through foreign key attributes), how should a repository (gateway) go about loading a tree of related entities? Should PostGateway.getLatestTen() also load the User entities for the author attribute of each Post, or should a separate method, PostGateway.getLatestTenWithAuthors(), do that?

Łukasz Duda

unread,
Nov 14, 2019, 2:22:38 PM11/14/19
to Clean Code Discussion
Hi Jordan,
Identity is not only database-related. Identity generated by database is only one of a few possible strategies to implement unique identity.

Vaugh Vernon in his book suggests, that one aggregate should refer to another by id.


I've heard, that an aggregate should contain as few information as possible, only the information needed to implement business rules, only the information in scope of transaction. Reference by identity causes better separation, less coupling, than direct reference to object, decreases the scope of transaction.

I've heard another rule, that only one aggregate can be modified in single transaction. Big aggregate holding references to many entities is symptom of poorly defined boundaries.

Regards
Łukasz
Reply all
Reply to author
Forward
0 new messages