c# - 抛出异常而不是处理返回
问题描述
我正在尝试重构一英里长的方法,并且正在考虑是否抛出 ReturnException 而不是调用返回。看我的例子:
当前一英里长的代码如下所示:
public void MyMileLongMethod()
{
//some logic
//some more logic
if (a == 10 && (b == "cool" || b == "super cool"))
{
//logic here
//more logic
//15 more lines of code.
return;
}
if (x && y || z==5)
{
//logic here
//more logic
//20 more lines of code.
return;
}
//more conditions like this that calls a return
// probable more logic here
}
我想用以下方式重构它:
public void MyRefactoredMethod()
{
try
{
DoLogic1(parameters);
ConditionOneMethod(parameters);
ConditionTwoMethod(parameters);
//more methods like above that throws a ReturnException
// probable more logic here
}
catch (ReturnException)
{
return;
}
}
void DoLogic1(parameters)
{
//some logic
//some more logic
}
void ConditionOneMethod(parameters)
{
if (a == 10 && (b == "cool" || b == "super cool"))
{
//logic here
//more logic
//15 more lines of code.
throw new ReturnException();
}
}
void ConditionTwoMethod(parameters)
{
if (x && y || z == 5)
{
//logic here
//more logic
//20 more lines of code.
throw new ReturnException();
}
}
问题:抛出异常并在调用的方法中捕获它,然后在 catch 中调用 return 是一种好习惯吗?如果,那么有一个常用的模式名称吗?如果这不是一个好习惯,还有其他方法吗?还是我下面的解决方案就是答案?
我有的另一个解决方案是,检查外部方法中的条件,然后调用执行逻辑的方法,然后调用 return,但在我看来,外部方法中有很多代码。
解决方案
我会赞成使用这种变体:
private void MyRefactoredMethod(...) {
...
if (...)
return; // was "continue;"
...
if (!ConditionOneMethod(...))
return;
...
}
private boolean ConditionOneMethod(...) {
...
if (...)
return false; // was a continue from a nested operation
...
return true;
}
推荐阅读
- mysql - 从两个表中获取字段的总和和差异
- android - 尽管缺少的 jar 在定义的 lib 文件夹中,但 Gradle 无法解析所有工件
- mysql - 需要关于我应该为我的颤振应用程序使用哪个数据库的建议
- google-apps-script - DML 不适用于连接到 google 表格的 bigquery 表
- excel - 如何获取 Microsoft Calculator 结果到单元格?
- react-native - 使用带有 React Native 的 Firebase 云消息传递无法获得振动或声音
- mysql - 如何从不可变数据库中选择数据的最佳方式?
- go - 如何使用反射创建参数实体
- reactjs - @react-google-maps/api - 加载地图阻塞了主线程
- r - 在 RStudio 中运行 pivot_wider() 时这些错误消息的含义是什么?