我正在实施串行通信协议。在这个实现的接收函数中,我有多个出口点,带有重复的代码用于清理。在结构/ OO编程语言的情况下,我不确定表达式SESE是否有效。我正在使用C ++。 这不是MCVE,而只是我在代码中的结构。代码看起来像:
bool receive()
{
bool status = false;
initializeCommunication();
if (receiveOneByteIsNotWhatExpected())
{
cleanupCode();
return status;
}
processFirstParam();
if (receiveTwoBytesIsNotWhatExpected())
{
cleanupCode();
return status;
}
processSecondParam();
if (receiveOneByteIsNotWhatExpected())
{
cleanupCode();
return status;
}
processThirdParam();
if (receiveFourBytesIsNotWhatExpected())
{
cleanupCode();
return status;
}
processFourthParam();
status = true;
cleanupCode();
return status;
}
我想重构它。一种方法是使用一种状态机,例如:
bool receive()
{
status = true;
state = START;
while (status && state != POSTENDED)
{
switch(state)
{
case START:
initializeCommunication();
state = RECEIVEFIRSTONEBYTE;
// fall-through
case RECEIVEFIRSTONEBYTE:
if (receiveOneByteIsNotWhatExpected())
{
status = false;
}
else
{
processFirstParam();
state = RECEIVESECONDTWOBYTES;
}
break;
case RECEIVESECONDTWOBYTES:
if (receiveTwoBytesIsNotWhatExpected())
{
status = false;
}
else
{
processSecondParam();
state = RECEIVETHIRDONEBYTE:
}
break;
case RECEIVETHIRDONEBYTE:
if (receiveOneByteIsNotWhatExpected())
{
status = false;
}
else
{
processThirdParam();
state = RECEIVEFOURTHFOURBYTES;
}
break;
case RECEIVEFOURTHFOURBYTES:
if (receiveFourBytesIsNotWhatExpected())
{
status = false;
}
else
{
processFourthParam();
state = ENDED;
}
break;
case ENDED:
status = true;
state = POSTENDED;
break;
}
}
cleanupCode();
return status;
}
编写上述代码的第三种方法是使用嵌套的if语句,它将生成嵌套if语句的四个级别,但这将是简洁的。 编写这种代码的优化方法是什么,以及每种代码的优缺点是什么。
答案 0 :(得分:1)
虽然标签和goto
的使用通常不受欢迎,但这通常是许多人认为可以使用的情况之一。
所以没有例如。
if (receiveOneByteIsNotWhatExpected())
{
cleanupCode();
return status;
}
...
你会有像
这样的东西if (receiveOneByteIsNotWhatExpected())
{
goto end;
}
在功能结束时:
processFourthParam();
status = true;
end:
cleanupCode();
return status;
}
这将最大限度地减少公共代码的重复,并且是“一次退货”或“单一进入,单一退出”原则的基石。
答案 1 :(得分:1)
清理守卫怎么样:
SELECT EMPID
FROM yourTable
GROUP BY EMPID
HAVING SUM(CASE WHEN Status NOT IN ('A', 'B') OR Status IS NULL THEN 1 ELSE 0 END) = 0 AND
COUNT(DISTINCT Status) = 2
内联函数:
bool receive()
{
bool status = false;
initializeCommunication();
struct CleanupGuard
{
~CleanupGuard()
{
cleanupCode();
}
} g;
if (receiveOneByteIsNotWhatExpected())
{
return status;
}
// [...]
}
循环方式:
namespace
{
inline bool doReceive()
{
// [...]
}
}
bool receive()
{
initializeCommunication();
bool status = doReceive();
cleanupCode();
return status;
}