Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Building Fluent API for method invocations

What do I have to do to say that InvokeMethod can invoke a method and when using special options like Repeat it shall exexute after the Repeat.

My problem for now is that the method will already exexute before it knows that it has to be called 100 times.

class Program
{
    static void Main()
    {
        const bool shouldRun = true;

        new MethodExecuter()
            .ForAllInvocationsUseCondition(!Context.WannaShutDown)
                .InvokeMethod(A.Process).Repeat(100)
                .When(shouldRun).ThenInvokeMethod(B.Process).Repeat(10)
            .ForAllInvocationsUseCondition(Context.WannaShutDown)
                .When(shouldRun).ThenInvokeMethod(C.Process);
    }
}

MethodExpression

public class MethodExpression
{
    private bool _isTrue = true;
    private readonly MethodExecuter _methodExecuter;
    public MethodExpression(bool isTrue, MethodExecuter methodExecuter)
    {
        _isTrue = isTrue;
        _methodExecuter = methodExecuter;
    }

    public MethodExecuter ThenInvokeMethod(Action action)
    {
        if (_isTrue)
        {
            action.Invoke();
            _isTrue = false;
        }
        return _methodExecuter;
    }
}

MethodExecuter

public class MethodExecuter
{
    private bool _condition;
    private int _repeat = 1;

    public MethodExpression When(bool isTrue)
    {
        return new MethodExpression(isTrue && _condition, this);
    }

    public MethodExecuter InvokeMethod(Action action)
    {
        if (_condition)
        {
            for (int i = 1; i <= _repeat; i++)
            {
                action.Invoke();
            }
        }
        return this;
    }

    public MethodExecuter ForAllInvocationsUseCondition(bool condition)
    {
        _condition = condition;
        return this;
    }

    public MethodExecuter Repeat(int repeat)
    {
        _repeat = repeat;
        return this;
    }
}
like image 221
Rookian Avatar asked Jun 07 '11 16:06

Rookian


1 Answers

Use a final method ("go", or "execute") to actually kick things off.

      new MethodExecuter()
        .ForAllInvocationsUseCondition(!Context.WannaShutDown)
            .InvokeMethod(A.Process).Repeat(100)
            .When(shouldRun).ThenInvokeMethod(B.Process).Repeat(10)
        .ForAllInvocationsUseCondition(Context.WannaShutDown)
            .When(shouldRun).ThenInvokeMethod(C.Process)
            .Go();
like image 181
Rob Avatar answered Sep 29 '22 17:09

Rob