0

When looking at some codebases, which heavily use inheritance or implementing interfaces, I often see some implementation classes or specific methods that basically call their superclass or supermethods and add some additional behaviour. So you can add your own business logic into some specific process (just like life-cycle methods or hooks in component-based frontend frameworks let you do this), e.g.

// Superclass --> Usually a class which is provided by some framework, etc.
class Car ...
 public method drive()...

// Some Subclass
class Mitsubishi extends Car
 public method driveExt() {
  super.drive();
  // Some custom behaviour
 }

and I was wondering if this is some kind of well-known pattern in object oriented design, because I can't seem to find something about it despite having seen this pattern in many codebases. So I basically want to know, if there is a name to this pattern.

Marcel N.
  • 57
  • 2
  • 10
  • It's not one of the established patterns (GoF etc.). Seems like an anti-pattern to me. Inheritance is usually garbage. I wouldn't try to imitate this, even in a codebase where it's prevalent. Methods should be verb phrases. You say "I drive a car", not "I driveExt a Mitsubishi". Seems all too easy to accidentally call the non-'ext' version. – Michael May 19 '22 at 11:29

1 Answers1

0

In my view, this is a kind of work around to reuse a behaviour of base class without violation of Liskov substitution principle. Something like this:

class Person 
{
    void Run(){ }
}

class Sportsman extends Person 
{
    void RunAtStadium()
    {
        if (isStadium)
           super.Run();
    }
}

I do not think that it is a good practice. There is no such pattern in software design patterns. It would be much better if code would like this:

public class Person
{
    public void Run() { }
}

public class Sportsman extends Person
{   
}

and then sportsmen will run at stadium:

public class Stadium
{
    public List<Sportsman> Sportsmen { get; set; } = new List<Sportsman>();

    public void AddSportsmanToLap(List<Sportsman> sportsmen) 
    {
        Sportsmen.AddRange(sportsmen);
    }

    public void RunCompetetion() 
    {
        foreach (Sportsman sportsman in Sportsmen)
            sportsman.Run();
    }
}
StepUp
  • 36,391
  • 15
  • 88
  • 148