【发布时间】:2013-12-03 07:24:46
【问题描述】:
我正在处理一些由于状态检查而难以重构的代码。我试图找出更好的方法来解决这个问题,这样我就可以保持我的代码干净/可读。这是代码的 sn-p:
int status = FAILED;
status = fn_action_one();
if (status != SUCCESS)
{
printf("ERROR: returned from fn_action_one()\n");
}
else
{
status = fn_action_two();
}
if (status != SUCCESS)
{
printf("ERROR: returned from fn_action_two()\n");
}
else
{
status = fn_action_three();
}
对我来说,问题是我现在想重构这段代码并循环遍历其中的一部分:
int status = FAILED;
status = fn_action_one();
if (status != SUCCESS)
{
printf("ERROR: returned from fn_action_one()\n");
}
else
{
// This task is now required to be done multiple times...
for (int i = 0; i < numLoop; i++)
{
status = fn_action_two(i); // Keeping track of the status here is now an issue
}
}
// If any of the looped action_two's had a fail this check should fail
if (status != SUCCESS)
{
printf("ERROR: returned from fn_action_two()\n");
}
else
{
status = fn_action_three();
}
这现在变得很困难,因为在循环时我想继续循环遍历所有 numLoop 次(无论是什么),但如果一个失败,状态应该保持失败。
有没有一种干净的方法可以做到这一点?或者也许有一个模式?
编辑:状态值的枚举
enum status_vals
{
SUCCESS = 0,
FAILED = -1,
FAILED_TIMEOUT = -2,
FAILED_FATAL = -3,
etc...
}
【问题讨论】:
-
FAILED和SUCCESS的值是多少? -
我将使用真实代码中的值添加一个枚举