1

我遇到过几次:

try {
  if (condition()) {
    return simpleFunction(with, some, args);
  } else {
    return complexFunction(with, other, args);
  }
catch (something) {
  // Exception thrown from condition()
  return complexFunction(with, other, args);
}

有什么方法(任何语言)可以避免重复调用 complexFunction?理想情况下不会掩盖代码的意图?

4

2 回答 2

1

如果是c#,你可以做...

    try
    {
        if (condition()) {
            return simpleFunction(with, some, args);
        }
    }
    catch
    {
        // Swallow and move on to complex function
    }

    return complexFunction(with, other, args);

更新以使条件异常继续向上堆栈

if (condition()) {
    try
    {
        return simpleFunction(with, some, args);
    }
    catch
    {
        // Swallow and move on to complex function
    }
}
return complexFunction(with, other, args);
于 2013-01-19T08:32:47.180 回答
0

condition()如果失败则抛出异常

try
{
  if (condition())
  {
    return simpleFunction();
  }
  throw conditionException();
}
catch(conditionException ce)
{
  return complexFunction();
}

正如已经很好地指出的那样,这不是编写代码的方式。然而,它确实解决了这个问题——并且在某种程度上它似乎与问题中“模式”的意图相匹配,即如果条件抛出异常或返回 false,则认为它已失败。

于 2013-01-19T08:45:06.193 回答