給定以下代碼,是否有更好的方法來構造它?循環中的嵌套條件
foreach(Thing item in SomeRandomList)
{
bool firstCondition = CalculateBool(item, someValue);
bool secondCondition = CalculateBool(item, someOtherValue);
//General things are done...
if(firstCondition || secondCondition)
{
//semi-specific things are done...
if(firstCondition)
{
//specific things are done...
}
else
{
//specific things are done...
}
}
}
另外,如果有更多的條件,即3:
foreach(Thing item in SomeRandomList)
{
bool firstCondition = CalculateBool(item, someValue);
bool secondCondition = CalculateBool(item, someOtherValue);
//imagine as many more as you want.
bool nthCondition = CalculateBool(item, lastOtherValue);
//General things are done...
if(firstCondition || secondCondition || nthCondition)
{
//semi-specific things are done...
if(firstCondition)
{
//specific things are done...
}
else if(secondCondition)
{
//specific things are done...
}
else
{
//specific things are done...
}
}
}
外部條件似乎如果你想具體的行執行任何情況下 –
冗餘對於特定的條件組合,你會陷入意大利麪。但就你的例子而言,西蒙是正確的 - 你的條件是相互排斥和優先考慮的,所以只要不把它們放在一起即可。 – Potatoswatter
您尚未提供足夠的信息來說明您要完成的任務,那麼如何才能說明是否有更好的方法來組織您的代碼呢? –