Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Common code when overriding abstract methods - Design issue

I've got an abstract class like this

public abstract Stuff
{
    public abstract void doStuff();
}

Several classes are extending Stuff, overriding doStuff(). doStuff() in general performs totally different tasks for each implementation but shares a common part.

Whats the best way to implement this?

I don't want to write someting like:

public void doStuff()
{
    doTheCommonPart();
    ...
}

in every extending class.

like image 628
Simbi Avatar asked May 18 '26 20:05

Simbi


2 Answers

You could use the Template Method Pattern:

public abstract Stuff
{
    public abstract void doStuff();

    public void doTheCommonPart() {
      // ...
    }

    // Template method
    public final void doIt() {
      doTheCommonPart();
      doStuff();
    }
}

Then, your client classes just have to call the template method doIt(). It will execute the common code part, as well as the concrete implementation of the abstract method doStuff().

like image 63
João Silva Avatar answered May 21 '26 09:05

João Silva


Either:

  1. Place the common code in a protected method in the Stuff class and call it from each implementation of doStuff; or

  2. Add the common code to your abstract Stuff class and call another abstract method.

E.g. (1)

public abstract Stuff  
{
    public abstract void doStuff();

    protected void commonCode() 
    {
      //...
    }
}

or (2)

public abstract Stuff
{
    public void doStuff() 
    {
      // Do the common stuff initially...
      // ...

      // Then call the subclass implementation
      doRealStuff();
    }

    public abstract void doRealStuff();
}
like image 37
Duncan Jones Avatar answered May 21 '26 10:05

Duncan Jones



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!