Home > Back-end >  Is Deep Class Hierarchies to solve version good?
Is Deep Class Hierarchies to solve version good?

Time:10-11

I have a abstract class BaseClass and extend class Class1 Class2 Class3 Class...
All the class has version concept.
The class hint is this

internal abstract class BaseClass
{
  internal abstract bool MethodA();
  internal abstract bool MethodB();
  ...
}
// you can imagine Class1 is version 1
internal class Class1 : BaseClass
{
  internal override bool MethodA() => ...; // do something belong Class1 version logic
  internal override bool MethodB() => ...; // do something belong Class1 version logic
  ...
}

Now, I have a problem with this.
When I want to upgrade my business logic to version 2,but the inner logic is half the same.
Is't used inherit possibled a good idea?

// you can imagine Class2 is version 2
internal class Class2 : Class1
{
  // the MethodA is the same with Class1, so the place didn't override
  internal override bool MethodB() => ...; // new logic different than Class1.MethodB
  ...
}

Have this problem because I think when n years after. This class is possible upgrade to version n,so that the inherit will be very deep.

// ex:
Class3 : Class2;
Class4 : Class3;
Class5 : Class4;
...

Or anyone have idea to solve the version issue?(Again, that have 90% the same and 10% different in each iterate)

Thanks!

CodePudding user response:

I think you could simply prefer composition over inheritance and used an appropriate design pattern for versioning.

If you want to stick to inheritance, then it is fine. Code duplication cant exist, you can do the following:

  1. Create new functions that the derived class will inherit but not override.
  2. Use the Open-Closed principle (part of SOLID), and let the client side deliver the logic through a delegate.
  3. Segregate concerns further and use dependency injection in the relevant classes that you concern may have duplicate code.

CodePudding user response:

Let's take step back and implement in most straight forward way:

public class Class1 : BaseClass
{ 
  public void MethodA() {...}
  public void MethodB() {...}
}

public class Class2 : BaseClass
{ 
  public void MethodA() {/* same as in Class1 */}
  public void MethodB() {...}
}

and now you want to avoid this code duplication.

So I would suggest going in direction of composition and define Class2 as wrapper around Class1 and continue this approach outwards:

public class Class2 : BaseClass
{ 
  private readonly BaseClass prevVersionClass;

  public Class2(BaseClass prevVersionClass)
  {
    this.prevVersionClass = prevVersionClass;
  }

  public void MethodA() { prevVersionClass.MethodA(); }
  public void MethodB() {...}
}
  • Related