gpt4 book ai didi

c# - 具有多个返回点的重构方法

转载 作者:可可西里 更新时间:2023-11-01 08:42:18 25 4
gpt4 key购买 nike

**编辑:下面有几个可行的选项。请根据您对此事的看法进行投票/评论。

我正在清理并向具有以下基本结构的 c# 方法添加功能:

    public void processStuff()
{
Status returnStatus = Status.Success;
try
{
bool step1succeeded = performStep1();
if (!step1succeeded)
return Status.Error;

bool step2suceeded = performStep2();
if (!step2suceeded)
return Status.Warning;

//.. More steps, some of which could change returnStatus..//

bool step3succeeded = performStep3();
if (!step3succeeded)
return Status.Error;
}
catch (Exception ex)
{
log(ex);
returnStatus = Status.Error;
}
finally
{
//some necessary cleanup
}

return returnStatus;
}

有很多步骤,在大多数情况下,步骤 x 必须成功才能继续执行步骤 x+1。现在,我需要添加一些始终在方法结束时运行的功能,但它取决于返回值。我正在寻找有关如何彻底重构它以达到预期效果的建议。显而易见的选择是将依赖于返回值的功能放在调用代码中,但我无法修改调用方。

一个选项:

    public void processStuff()
{
Status returnStatus = Status.Success;
try
{
bool step1succeeded = performStep1();
if (!step1succeeded)
{
returnStatus = Status.Error;
throw new Exception("Error");
}

bool step2succeeded = performStep2();
if (!step2succeeded)
{
returnStatus = Status.Warning;
throw new Exception("Warning");
}

//.. the rest of the steps ..//
}
catch (Exception ex)
{
log(ex);
}
finally
{
//some necessary cleanup
}
FinalProcessing(returnStatus);
return returnStatus;
}

我觉得这有点难看。相反,我可以直接从 performStepX() 方法中抛出。但是,这留下了在 processStuff() 的 catch block 中适当设置 returnStatus 变量的问题。您可能已经注意到,处理步骤失败时返回的值取决于失败的步骤。

    public void processStuff()
{
Status returnStatus = Status.Success;
try
{
bool step1succeeded = performStep1(); //throws on failure
bool step2succeeded = performStep2(); //throws on failure

//.. the rest of the steps ..//
}
catch (Exception ex)
{
log(ex);
returnStatus = Status.Error; //This is wrong if step 2 fails!
}
finally
{
//some necessary cleanup
}
FinalProcessing(returnStatus);
return returnStatus;
}

如果您有任何建议,我将不胜感激。

最佳答案

不要使用异常来控制程序的流程。就个人而言,我会保留代码原样。要在最后添加新功能,您可以这样做:

    public void processStuff()
{
Status returnStatus = Status.Success;
try
{
if (!performStep1())
returnStatus = Status.Error;
else if (!performStep2())
returnStatus = Status.Warning;

//.. More steps, some of which could change returnStatus..//

else if (!performStep3())
returnStatus = Status.Error;
}
catch (Exception ex)
{
log(ex);
returnStatus = Status.Error;
}
finally
{
//some necessary cleanup
}

// Do your FinalProcessing(returnStatus);

return returnStatus;
}

关于c# - 具有多个返回点的重构方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1645449/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com