c# – How do I design a class hierarchy to make it easy to add properties to the base class?

Question:

Comrades, tell me how in a decent society it is customary to solve such a problem:

We have, for example, such a class hierarchy

class A_Base
{
  int x;
  int y;

  public A_Base(int x, int y) 
  { 
    this.x = x;
    this.y = y;
  }
}

class A_First : A_Base
{
  string name;

  public A_First(int x, int y, string name):base(x,y) 
  { 
    this.name = name; 
  }
}

class A_Second : A_First
{
  string surname;

  public A_Second(int x, int y, string name, string surname):base(x,y,name)
  {
    this.surname = surname;
  }
}

Now we need to add one more property to A_Base (and, accordingly, initialize it in the constructor)

class A_Base
{
  int x;
  int y;
  int z;

  public A_Base(int x, int y, int z) 
  { 
    this.x = x;
    this.y = y;
    this.z = z;
  }
}

This means that we will have to change the definition of the constructor in the entire class hierarchy, adding a new parameter z there, although we do not change these constructors themselves – we only change the call to the parent. And somehow it's not very good.

class A_First : A_Base
{
  string name;

  public A_First(int x, int y, int z, string name):base(x,y,z) 
  { 
    this.name = name; 
  }
}

How is it customary for advanced PLO comrades to act in such cases? Create a separate class / structure that will be a parameter for the constructor?

class A_Init
{
  int x;
  int y;
  int z;
}

class A_Base
{
  int x;
  int y;
  int z;

  public A_Base(A_Init init) 
  { 
    this.x = init.x;
    this.y = init.y;
    this.z = init.z;
  }
}

or is there any other tricky pattern?

Answer:

This is one of the disadvantages of inheritance – if the parent class changes, then the changes will most likely affect all children. And nothing can be done about it. This disadvantage will be especially evident in long-term and large programs.

To avoid such things, you might consider replacing inheritance with composition, or familiarize yourself with SOLID design, or look at other paradigms such as Component-Oriented Programming .

In the latter, each class is built from components, inheritance is not used, respectively, the problem disappears, and the probability of errors is much less, but when there are many components, it will be difficult to navigate in them.

Scroll to Top