是否有可能使这种模式更干?

时间:2013-01-19 08:29:58

标签: exception language-agnostic control-flow

我遇到过这几次:

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?理想情况下,不会模糊代码的意图吗?

2 个答案:

答案 0 :(得分: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);

答案 1 :(得分:0)

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

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

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