我在各种项目中遇到过几次这个问题,我想知道是否有比我通常最终使用的解决方案更好的解决方案。
假设我们有一系列需要执行的方法,并且我们想知道其中一个方法是否出现问题并优雅地中断(可能撤消任何以前的更改......),我通常会执行以下操作(伪C#,因为这是我最熟悉的):
private bool SomeMethod()
{
    bool success = true;
    string errorMessage = null;
    success = TestPartA(ref errorMessage);
    if (success)
    {
        success = TestPartB(ref errorMessage);
    }
    if (success)
    {
        success = TestPartC(ref errorMessage);
    }
    if (success)
    {
        success = TestPartD(ref errorMessage);
    }
        //... some further tests: display the error message somehow, then:
        return success;
}
private bool TestPartA(ref string errorMessage)
{
    // Do some testing...
    if (somethingBadHappens)
    {
       errorMessage = "The error that happens";
       return false;
    }
    return true;
}
我只是想知道(这是我的问题)是否有更好的方法来应对这种事情。我似乎最终if为一些看起来应该更流畅的东西写了很多陈述。
有人建议我对一组委托函数进行循环,但我担心这会过度设计解决方案,除非有一种干净的方法可以做到这一点。