Iai*_*ser 3 c# design-patterns if-statement code-readability
假设我有一个冗长,复杂的条件列表,必须为true才能运行if语句.
if(this == that && foo != bar && foo != that && pins != needles && apples != oranges)
{
DoSomethingInteresting();
}
Run Code Online (Sandbox Code Playgroud)
通常情况下,如果我被迫做这样的事情,我会把每个语句放在自己的行上,如下所示:
if
(
this == that
&& foo != bar
&& foo != that
&& pins != needles
&& apples != oranges
)
{
DoSomethingInteresting();
}
Run Code Online (Sandbox Code Playgroud)
但我仍觉得这有点乱.我很想将if语句的内容重构为它自己的属性
if(canDoSomethingInteresting)
{
DoSomethingInteresting();
}
Run Code Online (Sandbox Code Playgroud)
但是那只是将所有的混乱移动到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();
}
Run Code Online (Sandbox Code Playgroud)
在我看来,把混乱变成一个属性或一个方法并不是一个坏主意.这样它就是自包含的,你执行if(..)检查的主要逻辑变得更具可读性.特别是如果要检查的条件列表很大,最好是在属性中,这样如果您需要重新使用,而不是复制该检查.
if(IsAllowed)
{
DoSomethingInteresting();
}
Run Code Online (Sandbox Code Playgroud)