Home > other >  how to order methods calls inside a class depending on a boolean
how to order methods calls inside a class depending on a boolean

Time:11-05

in a class I have 3 private methods (two voids and one that returns an id).. depending on a boolean variable I need to call this methods in a specific order.

I can simply do:

if(booleanIstrue){ 

var id = method1(); 
method2(); method3(); 
} else { 
method2(); 
method3(); 
id = method1(); 

}

but is there is a better way to do this ?

CodePudding user response:

I assume those methods are not idempotent if the order of calling matters. I'd write something like this.

type id; // declare id with a proper type
if (boolean) id = method1();
method2();
method3();
if (!boolean) id = method1();

If method1() is idempotent and you don't care about calling it twice then.

var id = method1();
method2();
method3();
if (!boolean) id = method1();

CodePudding user response:

You can do it with this way but really, if you only have two cases (true, false) and a few methods, I would stick with your code or the one from Infixo.

public class MyClass
{
    public MyClass()
    {
        InitSequences();
    }

    public int Id { get; set; }

    protected List<Action> SequenceOne
    { get; set; }
    protected List<Action> SequenceTwo
    { get; set; }

    public void InitSequences()
    {
        SequenceOne = new List<Action>()
        {
            () => Id = Method1(),
            () => Method2(),
            () => Method3()
        };

        SequenceTwo = new List<Action>()
        {
            () => Method2(),
            () => Method3(),
            () => Id = Method1()
        };
    }

    public void OrderedExecution(bool order)
    {
        if (order)
            Execute(SequenceOne);
        else
            Execute(SequenceTwo);

    }

    public void Execute(IEnumerable<Action> actions)
    {
        foreach (var action in actions)
            action();
    }


    public int Method1()
    {
        return 1;
    }

    protected void Method2()
    {

    }

    protected void Method3()
    {
    }

}

It is just a very simple example of "lists of functions" since you asked for one but this solution could be less lisible for other developpers and becomes interresting only if you have a lot of methods to order and/or a lot of cases.

  • Related