Search code examples
oopinheritancedesign-patternscomposition

Design Pattern: Inheritance or Composition


I have 2 classes A and B, both of which have properties X and Y; but class B also has another property, Z. Classes A and B are completely unrelated to one another, they just share properties X and Y.

Inheritance

class A
{
    public int X;
    public int Y;
}

class B : A
{
    public int Z;
}

Class B does not have a "is-a" relationship to class A, so it breaks inheritance principals is OOP.

Composition

class A
{
    public int X;
    public int Y;
}

class B
{
    public A ObjA;
    public int Z;
}

Class B does not have a "has-a" relationship to class A so it breaks composition principals is OOP.

Without duplicate code, should I use inheritance or composition (even though they brake the principles of OOP) or is there another design pattern? I personally think that using inheritance is going to be the lesser of the evils because of readability.


Solution

    1. Since Class B does not have a "has-a" relationship to class A .. so "Composition" should not be used.

    2. You can use OOP Inheritance way as you designed. It does not break OOP principles as you said. Class A & B are not 100% unrelated. They have common properties so OOP Inheritance way is acceptable. Remember that OOP does not require inheritance of Method members.

    BUT for your case.You should duplicate Properties declaration so changes of a class does not affect the other.

    class A
    {
        public int X;
        public int Y;
    }
    
    class B
    {
        public int X;
        public int Y;
        public int Z;
    }