Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Abstract classes or partial?

I have a number of tasks which can be carried out by similar (yet slightly different) classes which all share a common set of functionality.

My intention is to extract this functionality into a parent class, and because I don't want this to be implemented itself I've marked it abstract.

However all of the calling classes call a single method - which used to contain the extracted common functionality. I don't want to override the parent class method but I want it to be executed in addition to what is defined in the child class.

I initially thought this was a job for a partial method, but I think this will break semantics somewhat. So what is the best way forward for me? Experiencing a bit of tunnel vision here.

like image 324
m.edmondson Avatar asked Jan 18 '23 06:01

m.edmondson


1 Answers

You could do it like this:

public abstract class Parent
{
    public void TheSingleMethod()
    {
        CommonFunctionality();

        InternalDo();
    }

    protected abstract void InternalDo();

    private void CommonFunctionality()
    {
        // Common functionality goes here.
    }
}

public class Derived : Parent
{
    protected override void InternalDo()
    {
        // Additional code of child goes here.
    }
}
like image 118
Daniel Hilgarth Avatar answered Jan 24 '23 13:01

Daniel Hilgarth