Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

designing virtual methods

Tags:

c#

virtual

I wonder under what circumstances you would choose the first or the second design :

First design : the child method have to call the base method

public abstract class Base
{
    public virtual void Enable() { IsEnable = true;  }
    public virtual void Disable() { IsEnable = false; }
    public bool IsEnable { get; private set; }
}

public class Child : Base
{
    public override void Enable() { /* do stuffs */  base.Enable(); }
    public override void Disable() {  /* do stuffs */ base.Disable(); }
}

Second design : a virtual method is used to be sure the child do not forget to call the base

public abstract class Base
{
    public void Enable()
    {
        IsEnable = true;
        OnEnable();
    }

    public void Disable()
    {
        IsEnable = false;
        OnDisable();
    }

    public bool IsEnable { get; private set; }
    public virtual void OnEnable() {}
    public virtual void OnDisable() {}
}

public class Child : Base
{
    override void OnEnable() { /* do stuffs */ }
    override void OnDisable() { /* do stuffs */ }
}

Thanks

like image 543
noon Avatar asked Jan 22 '23 16:01

noon


1 Answers

It depends if you really want to make sure IsEnable gets set or not. If you can imagine scenarios in which the user doesn't want to set it, then I suppose you leave it up to them to call the base method. Otherwise, do it for them.

like image 193
mqp Avatar answered Jan 31 '23 16:01

mqp