oopclass-design

Is it good to subclass a class only to separate some functional parts?


Suppose we have abstract class A (all examples in C#)

public abstract class A
{
    private Foo foo;

    public A() { }

    public void DoSomethingUsingFoo()
    {
        //stuff
    }

    public void DoSomethingElseUsingFoo()
    {
        //stuff
    }

    //a lot of other stuff...
}

But we are able to split it into two classes A and B:

public abstract class A
{
    public A() { }

    //a lot of stuff...
}

public abstract class B : A
{
    private Foo foo;

    public B() : base() { }

    public void DoSomethingUsingFoo()
    {
        //stuff
    }

    public void DoSomethingElseUsingFoo()
    {
        //stuff
    }

    //nothing else or just some overrides of A stuff
}

That's good, but we are 99.99% sure, that no one will ever subclass A, because functionality in B is very important.

Is it still good to have two separate classes only to split some code into two parts and to separate functional elements?


Solution

  • To me, your inheritance doesn't serve any purpose of code reuse and polymorphism. Inheritance is not meant to be used solely to split a big piece of code into two places just for easy reading. The introduction of an extra layer brings more complication than clearification so I don't think it is the thing you should do here.

    I would suggest you leave class A as what it is and later when you find a stronger reason to refactor, you do it then. At that moment, I also agree with Mark that you should consider composition than inheritance.