Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to force inheriting class's method implementation to call base method before invoke own implantation?

I wrote some not sealed class that contain 3 virtual public method and one private method.

And i make this class public that all my develop group member could use this class ( include inherits and override the virtual public methods ) .

One of the private method name is 'PrivateMethod77()'.

Each time the public method 'PublicMethod77()' is call => the 'PrivateMethod77' is call in the first line of the method implementation ( after this line there are more implication logic ).

I want to keep this logic and 'force' the inherits and override of the method PublicMethod77 to call the PrivateMethod77 method as the first line of the PublicMethod77

Is there a way to do it ?

like image 357
Yanshof Avatar asked Oct 21 '25 02:10

Yanshof


1 Answers

I don't think that you can enforce the inheriting classes to always first call a method's super implementation, but:

Normally I use a Template method pattern for cases like this:

public abstract class TemplateEnforcer
{
    private void TheSame()
    {
        Console.WriteLine("Everyone calls me;");
    }

    public void TemplateMethod()
    {
        this.TheSame();
        this.NeedsImplementation();
    }

    protected abstract void NeedsImplementation();
}

public class TemplateImplementer : TemplateEnforcer
{
    protected override void NeedsImplementation()
    {
        Console.WriteLine("Implemented in TemplateImplementer");
    }
}

Code output for this call new TemplateImplementer().TemplateMethod():

    //Everyone calls me;
    //Implemented in TemplateImplementer

Template method pattern benefits:

  1. Implementation of abstract method is forced.
  2. The code is kept DRY.
  3. Bugs are avoided and devs are guided in their development.
like image 53
Markus Weninger Avatar answered Oct 23 '25 17:10

Markus Weninger



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!