【问题标题】:Dealing with Sequence of dependent Functions处理依赖函数的序列
【发布时间】:2017-05-20 18:27:46
【问题描述】:

我有几个依赖远程资源返回结果的函数。 这个远程资源有很多我无法更改的错误或意外响应。 有一系列函数,每个函数都依赖于之前函数的结果。 每个函数的逻辑是不同的。

例如:

bool remoteFunction(string resource, string parameter = "")
{
// for example request
//for simplicity this is considered a request, but each function has different logic
return request.Url("example.com" + resource, parameter);
}

var firstResult = remoteFunction("a");                  //1st step
var secondResult = remoteFunction("b", firstResult);    //2nd step
var thirdResult = remoteFunction("c", secondResult);    //3rd step
var fourthResult = remoteFunction("d", thirdResult);    //4rth steo

我想做的是:

  • 继续重试执行该函数,直到它返回我们想要的结果。 这可以在函数内部或外部完成。
  • 我希望能够 从一个函数跳回前一个函数并继续 流量。即:从第 4 步跳到第 2 步并从 在那里。

最好的设计是什么?

感谢您的帮助


澄清: 更清楚地说,我只想在函数抛出异常时返回序列。 IE: 如果第 4 个函数抛出异常,我必须回到第 1 个并从那里继续。

【问题讨论】:

  • 从来没有最好的设计。到目前为止你有什么想法?
  • 要做你想做的事,你需要异步运行每个函数。然后你需要能够选择一个函数来运行。可以通过将代码放入 switch 块中来完成选择,每个函数都有不同的情况。
  • @jdweng 这些功能需要按顺序运行。

标签: c# .net design-patterns architecture


【解决方案1】:

不清楚它们是否需要按顺序运行。这是代码

            var firstResult;
            var secondResult;
            var thirdResult;
            var fourthResult;
            int start = 3;
            for (int i = start; i < 4; i++)
            {
                switch (i)
                {
                    case 0 :
                        firstResult = remoteFunction("a"); 
                        break;
                    case 1:
                        secondResult = remoteFunction("b", firstResult);
                        break;
                    case 2:
                        thirdResult = remoteFunction("c", secondResult);
                        break;
                    case 3:
                        fourthResult = remoteFunction("d", thirdResult);
                        break;
                }
            }

【讨论】:

  • 我认为这是不完整的; OP提到每个函数都依赖于序列中前一个函数的结果,但这个答案似乎并没有解决问题的那一部分。
  • 从描述听起来好像操作不需要重复通过的方法。所以他想从失败的函数中继续。
  • 再次阅读我的评论;问题是通过将前一个函数的 result 作为参数传递给下一个函数来按顺序调用函数。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-06-27
  • 2011-09-03
相关资源
最近更新 更多