lundi 24 mai 2021

How to enforce respect method execution order access in c#

Long story short, i have following class:

   public class FlowBasePipeline<T>{
   private List<StepBaseBusiness<T>> stepList = new List<StepBaseBusiness<T>>();
    
        public void Push(StepBaseBusiness<T> step)
            {
                stepList.Add(step);
            }
    
             public void Trigger(T result)
            {
                foreach (var step in stepList )
                {
                    result = step.Execute(result);
                    if (!result.IsSuccess)
                    {
                        break;
                    }
    
                }
            }
}

What I'm looking for is forcing programmer to call Push method in the first place and then give them access to Trigger method, in this case following scenario is not allowed

var pipeline=new FlowBasePipeline<MyStepResult>();
pipeline.Trigger()// Trigger method is not recognized

we should first call Push method

var pipeline=new FlowBasePipeline<MyStepResult>();
pipeline.Push(new MyStep()).Trigger()//Now Trigger is recognized

What I've done:

I applied explicit interface method implementation as follows to get it to work:

public interface IBasePipeline<T> where T:BaseResult,new()
{
    void Trigger();
    IBasePipeline<T> Push(StepBaseBusiness<T> step);
}


  public class FlowBasePipeline<T>:IBasePipeline<T> where T:BaseResult,new()
   {
          private List<StepBaseBusiness<T>> stepList = new List<StepBaseBusiness<T>>();
        
            public IBasePipeline<T> Push(StepBaseBusiness<T> step)
                {
                    stepList.Add(step);
                    return this;
                }
        
                void IBasePipeline<T>.Trigger(T result)
                {
                    foreach (var step in stepList )
                    {
                        result = step.Execute(result);
                        if (!result.IsSuccess)
                        {
                            break;
                        }
        
                    }
                }
    }

Now it works well and we don't have access to Trigger method before Push method, but from my prospective it's not a good way as we might need more level of orders and i don't know how it could be done in this way.

Is there any pattern or strategy to implement this kind of orders?

Update:

we need to call push method multiple time

var pipeline=new FlowBasePipeline<MyStepResult>();
pipeline.Push(new MyStep1()).Push(new MyStep2()).Trigger();

Aucun commentaire:

Enregistrer un commentaire