Search code examples
c#oopcomposition

OOP composition


I have a question regarding OOP composition.

Let's say that a mother has 0 or plus children, and a child has one and only one biologic mother.

To illustrate it, I did the following :

public class Mother : ObservableObject
{
    // [...]

    ObservableCollection<Child> Children {get; set;}
}

public class Child : ObservableObject
{
    public Child(Mother mother)
    {
        this.Mother = mother;

        // Adding the child to the mother's children collection
        mother.Children.Add(this);
    }

    public Mother Mother {get; set;}
}

but I wonder if it's okay to automatically add the child to the mother's collection, or if I should go with the following :

Mother mother = new Mother();

Child child = new Child(mother);
mother.Children.Add(child);

Thanks :)


Solution

  • I'd prefer,

    public class Mother : ObservableObject
    {
        // ...
    
        public Child GiveBirth()
        {
            var newBorn = new Child(this);
            this.Children.Add(newBorn);
            return newBorn;
        }
    
        // ...
    }