我有一个 C++ 程序,在许多不同的 .cpp 文件中,我执行如下操作:
if (!thing1.empty() && !thing2.empty())
{
if (thing1.property < thing2.property)
return func1();
else if (thing2.property < thing1.property)
return func2();
else
return func3();
}
else if (!thing1.empty())
{
return func1();
}
else if (!thing2.empty())
{
return func2();
}
else
{
return func4();
}
如果 thing1 大于 thing2,我尝试以一种方式执行 func,如果情况相反,则向后执行 func,但如果不存在,那么我只对那一半执行 func。如果两者都不存在,我会做一些完全不同的事情。每次我使用此模式时,属性、函数和返回类型都不同。对于我想要做的事情,有比这种丑陋的混乱的嵌套 if 语句更好的设计吗?
EDIT:意识到我的示例代码过于简单化。这是我的一些真实代码,希望能更好地解释问题(尽管它更混乱):
if (!diamondsOnly.empty() && !clubsOnly.empty())
{
if (diamondsOnly.size() < clubsOnly.size())
{
if (passHighCards(player.hand, getHighCards(Card::DIAMONDS), result))
return result;
if (passHighCards(player.hand, getHighCards(Card::CLUBS), result))
return result;
}
else if (clubsOnly.size() < diamondsOnly.size())
{
if (passHighCards(player.hand, getHighCards(Card::CLUBS), result))
return result;
if (passHighCards(player.hand, getHighCards(Card::DIAMONDS), result))
return result;
}
else
{
if (diamondsOnly.back().value > clubsOnly.back().value)
{
if (passHighCards(player.hand, getHighCards(Card::DIAMONDS), result))
return result;
if (passHighCards(player.hand, getHighCards(Card::CLUBS), result))
return result;
}
else
{
if (passHighCards(player.hand, getHighCards(Card::CLUBS), result))
return result;
if (passHighCards(player.hand, getHighCards(Card::DIAMONDS), result))
return result;
}
}
}
else if (!diamondsOnly.empty())
{
if (passHighCards(player.hand, getHighCards(Card::DIAMONDS), result))
return result;
}
else if (!clubsOnly.empty())
{
if (passHighCards(player.hand, getHighCards(Card::CLUBS), result))
return result;
}