Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to modify method return value in all derived classes?

Imagine you have a class hierarchy as:

class Base
{
    public virtual string GetName()
    {
        return "BaseName";
    }
}

class Derived1 : Base
{
    public override string GetName()
    {
        return "Derived1";
    }
}

class Derived2 : Base
{
    public override string GetName()
    {
        return "Derived2";
    }
}

In most appropriate way, how can I write the code in a way that all "GetName" methods adds "XX" string to return value in derived class?

For example:

         Derived1.GetName returns "Derived1XX"

         Derived2.GetName returns "Derived2XX"

Changing the code of GetName method implementation is not good idea, because there may exist several derived types of Base.

like image 531
Ahmet Altun Avatar asked Dec 12 '22 03:12

Ahmet Altun


1 Answers

Leave GetName non-virtual, and put the "append XX" logic in that function. Extract the name (without "XX") to a protected virtual function, and override that in the child classes.

class Base
{
    public string GetName()
    {
        return GetNameInternal() + "XX";
    }

    protected virtual string GetNameInternal() 
    {
        return "BaseName";
    }
}

class Derived1 : Base
{
    protected override string GetNameInternal()
    {
        return "Derived1";
    }
}

class Derived2 : Base
{
    protected override string GetNameInternal()
    {
        return "Derived2";
    }
}
like image 88
Blorgbeard Avatar answered Jan 05 '23 13:01

Blorgbeard