lundi 15 juin 2020

Guideline for writing callbacks via polymorphic method, delegate-type parameterized method or event handler

I am confused in deciding whether I should use

  • a polymorphic (via overriding the virtual method A) method.
  • a delegate-type-parameterized method B.
  • an event C.

when writing callbacks.

class Base
{
    protected virtual void A() => Console.WriteLine("Base's extra jobs.");
    public void Do(Action B = null)
    {
        Console.WriteLine("Base's main jobs.");

        // and call the optional jobs
        A();
        B?.Invoke();
        C?.Invoke();
    }
    public event Action C;
}


class Derived : Base
{
    protected override void A()
    {
        base.A();

        Console.WriteLine("Derived's extra jobs.");
    }
}

class Test
{
    static void Main()
    {
        Derived d = new Derived();
        d.C += () => Console.WriteLine("C");
        d.Do(() => Console.WriteLine("B"));
    }
}

Question

Is there any commonly used guideline for agile programmers?

Aucun commentaire:

Enregistrer un commentaire