Note that there are some explanatory texts on larger screens.

plurals
  1. PODomain Driven Design - Parent child relation pattern - Specification pattern
    primarykey
    data
    text
    <p>I was wondering which of the following is considered to be a best practice when dealing with parent child relationships.</p> <p>1) The following example seems to be a common practice, but when creating an instance of a child, it will be in an invalid state as long as it is not added to the parent. Couldn't this lead to problems regarding validation etc.</p> <pre><code>public class Parent { private ICollection&lt;Child&gt; children; public ReadOnlyCollection Children { get; } public void AddChild(Child child) { child.Parent = this; children.Add(child); } } public class Child { internal Parent Parent { get; set; } public Child() { } } </code></pre> <p>2) The next sample would take care that a child must always be related to its parent.</p> <pre><code>public class Parent { private ICollection&lt;Child&gt; children; public ReadOnlyCollection Children { get; } public Child CreateChild() { var child = new Child(); child.Parent = this; children.Add(child); return child; } } public class Child { internal Parent Parent { get; set; } internal Child() { } } </code></pre> <p>3) In the last example that child takes care of the relation to its parent itself.</p> <pre><code>public class Parent { private ICollection&lt;Child&gt; children; public ReadOnlyCollection Children { get; } public void AddChild(Child child) { child.Parent = this; children.Add(child); } } public class Child { public Parent Parent { get; set; } public Child(Parent parent) { this.Parent = parent; } } </code></pre> <p>Which pattern is considered the best? I believe that pattern 2 might be the best since then a child can never exist without a relation to its parent. This would make it easier e.g. when implementing a specification pattern that might do things like:</p> <pre><code>public class ChildSpecification { bool IsSatisfiedBy(Child child) { return child.Parent.Children.Where(someCondition).Count &gt; 0; } } </code></pre> <p>The above specification can only work if a child has a parent.</p> <p>What do you think? Do you know better ways? Thanks in advance</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload