我正在尝试重构一英里长的方法,并考虑是否抛出一个ReturnException而不是调用return。请看我的示例:
当前一英里长的代码如下所示:
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();
}
}
如果这不是一个好的做法,有没有其他办法呢?或者我的解决方案就是下面的答案?