mardi 27 mars 2018

How to include properties via composition?

After having to refactor the inheritance chain in my current project for the third time I typed "Inheritance sucks" into google and found that the problem I'm having is not uncommon and composition is a recommended alternative solution.

I understand how you can use composition to add behavior in form of functions, but I'm having problems to come up with ways to add properties by the same means.

Let's say I want to model tree nodes. Every node has at least the properties name and description.

class Node {
   public string Name { get; set; }
   public string Description { get; set; }
}

Other more specific nodes would inherit those properties, like so:

class StructuredNode : Node {
   public List<Node> Children;
}

How could I archive similar re-usability of the property code without relying on inheritance and the problems that come with it?
Is there a design pattern for this or do I have to use inheritance in such a case?

Thanks in advance!

Aucun commentaire:

Enregistrer un commentaire