Is Aggregate Root with Deep Hierarchy appropriate in DDD?

后端 未结 2 1934
无人及你
无人及你 2021-01-02 19:46

I have a system where a user answers question in a form. I have objects representing this model but I am not quite sure how to organize these objects in terms of DDD.

2条回答
  •  没有蜡笔的小新
    2021-01-02 20:18

    Yes, deep hierarchy is fine in DDD.

    Is that OK that I end up with a very extensive aggregate? - if the reality is that complex, and your domain model is as best as you can figure out, you will end up with a complex aggregate root.

    Yep, Form should be aggregate root.

    all other objects should be value objects - wrong, all other objects should be non-aggregate root entities (with Id) without a repository to fetch them. Value object does not have an Id, and an equality of value objects is determined only by its attribute values, not by equality of Ids (more info here).

    In this case FormRepository will be cluttered with all kinds of CRUD methods for child objects - no, a repository should contain only methods regarding aggregate root, i.e. Get , Save where T : IAggregateRoot, once you get an instance of an aggregate root, you can traverse via attributes and methods to get what you need. Example:

    var formId = 23;
    var form = _formRepository.Get(formId);
    var firstGroup = form.Sections.First().Group().First();
    

    or better

    var groupIndex = 1;
    var firstGroup = form.GetGroupAt(groupIndex);
    

    where

    public Group GetGroupAt(int groupIndex)
    {
        Sections.First().Group().ElementAt(groupIndex);
    }
    

    I believe such representation can easily lead to performance issues - if you use CQRS, you gonna be calling some Form domain method from command handler, and if you use NHibernate for entity persistence, it will by default use lazy loading, and would load only Form from DB, and then it would load only entities you really touch, so for instance Sections.First() would load all sections from DB, but not groups and the rest. For querying, you would create a FormDto (data transfer object) and other possibly flattened dtos to get data in the form you need (which might be different from your entities structure and UI might drive the dto structure). Have a look at my blog for info regarding DDD/CQRS/NHibernate/Repository

提交回复
热议问题