Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Object Orientated Design Parent / Child Relationship

Tags:

c#

oop

This is a general best practice question about creating parent / child relationships with objects.

Let's say I have Wheel and Car objects and I want to Add a Wheel object to car object

public class Car{

    private List<Wheel> wheels = new List<Wheel>();

    void AddWheel ( Wheel WheelToAdd)
        {
            wheels.Add(WheelToAdd)
            //Some Other logic relating to adding wheels here
        }
    }
}

So far so good. But what if I want to have a Car property of my wheel to say which parent car it relates to. Something like this

 public class Wheel {

     private Car parentCar;
     public Car 
     {
        get
        {
         return parentCar
        }

  }

}

When adding the wheel to the car, at which point would you set the parent property of the Wheel? You could set it in the Car.AddWheel method, but then the Car Property of the Wheel object would have to be Read/Write and then you could set it outside of the AddWheel method, creating an inconsistency.

Any thoughts, many thanks in advance

like image 550
Mark 909 Avatar asked Oct 06 '10 16:10

Mark 909


1 Answers

A better design methodology, (Domain Driven Design) specifies that you should first decide what the domain model requirements are for these entities... Not all entities need to be independantly accessible, and if Wheel falls into this category, every instance of it will always be a child member of a Car object and you don't need to put a Parent property on it... Car becomes what is referred to as a root entity, and the only way to access a Wheel is through a Car object.

Even when the Wheel object needs to be independantly accessible, the domain model requirements should tell you what the usage patterns require. Will any Wheel ever be passed around as a separate object, without it's parent ? In those cases is the Car parent relevant? If the identity of the parent Car is relevant to some piece of functionality, why aren't you simply passing the complete composite Car object to that method or module? Cases where a contained composite object (like a Wheel) must be passed on it's own, but the identity of the parent (the object it is part of) is needed and/or relevant, are in fact not a common scenario, and approaching your design using the above type of analysis can save you from adding unnessary code to you system.

like image 126
Charles Bretana Avatar answered Nov 14 '22 23:11

Charles Bretana