我有一个 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 语句更好的设计?
编辑:意识到我的示例代码过于简单化了。这是我的一些真实代码,希望能更好地解释问题(尽管它更混乱):
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;
}