假设我有一个长而复杂的条件列表,这些条件必须为真才能运行 if 语句。
if(this == that && foo != bar && foo != that && pins != needles && apples != oranges)
{
DoSomethingInteresting();
}
通常,如果我被迫做这样的事情,我只会将每个语句放在自己的行上,如下所示:
if
(
this == that
&& foo != bar
&& foo != that
&& pins != needles
&& apples != oranges
)
{
DoSomethingInteresting();
}
但是我还是觉得这有点乱。我很想将 if 语句的内容重构为它自己的属性,如下所示
if(canDoSomethingInteresting)
{
DoSomethingInteresting();
}
但这只是把所有的混乱都转移了进去canDoSomethingInteresting()
,并没有真正解决问题。
正如我所说,我的 goto 解决方案是中间的解决方案,因为它不会像最后一个那样混淆逻辑,并且比第一个更具可读性。但一定有更好的办法!
回应 Sylon 评论的示例
bool canDoSomethingInteresting
{
get{
//If these were real values, we could be more descriptive ;)
bool thisIsThat = this == that;
bool fooIsntBar = foo != bar;
bool fooIsntThat = foo != that;
return
(
thisIsThat
&& fooIsntBar
&& fooIsntThat
);
}
}
if(canDoSomethingInteresting)
{
DoSomethingInteresting();
}