如何通过多个步骤跟踪状态
how to keep track of status through many steps
我正在处理一些代码,由于它的状态检查,很难重新考虑这些代码。我正试图找出更好的方法来解决这个问题,这样我就可以保持代码的干净/可读性。下面是代码的一个片段:
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
循环(无论是什么),但如果一个失败,状态应该保持失败。
有干净的方法吗?或者这可能有一个模式?
EDIT:状态值的枚举
enum status_vals
{
SUCCESS = 0,
FAILED = -1,
FAILED_TIMEOUT = -2,
FAILED_FATAL = -3,
etc...
}
模式是使用异常处理。如果不能修改fn_action_xxx(),则编写包装
void my_action_one()
{
int status = fn_action_one();
if (status != SUCCESS)
throw std::runtime_error("ERROR: returned from fn_action_one()");
}
...
try
{
my_action_one();
for (int i = 0; i < numLoop; i++)
{
my_action_two(i);
}
my_action_three();
}
catch (const std::exception& e)
{
printf("%sn", e.what());
}
状态检查的脆弱性是异常的动机之一。通过将错误处理与程序的主流分离,您可以获得更清晰的代码。
作为一种"C"方法,我将使用宏和goto的组合。
#define CHECK(expr)
{
if( SUCCESS != (status = expr) ){
printf("ERROR: returned from " #EXPR "n");
goto End
}
}
int status = FAILED;
CHECK(fn_action_one());
End:
return status;
在循环中,我会做
if (status != SUCCESS)
{
status = fn_action_two(i);
}
如果您想尽可能紧密地维护当前的代码结构,并最大限度地减少实现所需功能所需的更改,您可能会添加一个布尔值来跟踪循环中是否有任何调用失败,然后在此基础上设置status
:
int status = FAILED;
status = fn_action_one();
if (status != SUCCESS)
{
printf("ERROR: returned from fn_action_one()n");
}
else
{
bool failed = false;
// This task is now required to be done multiple times...
for (int i = 0; i < numLoop; i++)
failed |= (fn_action_two(i) == FAILED);
}
if (failed)
status = FAILED;
// 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();
}
相关文章:
- 光线跟踪器灯光反射错误
- Constexpr替代了新的放置方式,可以让内存中的对象保持未初始化状态
- 人脸跟踪arduino代码的优化
- 我不断收到 [错误] ID 返回 1 退出状态错误,但看不到问题所在
- OSX MetalKit CVMetalTextureCacheCreateTextureFromImage失败,状态:
- 跟踪滚动条上的鼠标事件
- std::future_error:无关联状态
- 如何使用新运算符跟踪在循环中创建的 QLabel
- 如何避免LED在循环状态变化中闪烁?
- boost 是否有按特殊类型值编码状态"compact optional"?
- C++:跟踪类对象
- 用于解析 win64 堆栈跟踪的命令行客户端(可以访问符号服务器)
- 为什么系统函数总是在C++中返回已转移的退出状态?
- 跟踪日志中的T.11803()是什么意思?
- C++ 中的编译错误:未定义对"主"的引用 collect2:错误:ld 返回 1 个退出状态
- MATLAB:跟踪imufilter对象中的状态变化
- 如何跟踪Windows 7是否在C ++中以编程方式进入睡眠或休眠状态,就像在Windows XP中所做的那样
- 如何通过多个步骤跟踪状态
- Opencv光流跟踪:停止状态
- Git 状态显示奇怪的未跟踪"path_of_filer"文件,如何通过命令行删除