在我的C#代码中,我有一个if语句,最开始看起来很无害:
if((something == -1) && (somethingelse == -1) && (etc == -1)) {
// ...
}
它在不断增长。我认为现在里面肯定有20个条款。
我应该如何处理这个问题?
在我的C#代码中,我有一个if语句,最开始看起来很无害:
if((something == -1) && (somethingelse == -1) && (etc == -1)) {
// ...
}
它在不断增长。我认为现在里面肯定有20个条款。
我应该如何处理这个问题?
尽可能使用门。
if语句
if(bailIfIEqualZero != 0 &&
!string.IsNullOrEmpty(shouldNeverBeEmpty) &&
betterNotBeNull != null &&
!betterNotBeNull.RunAwayIfTrue &&
//yadda
重构后的版本
if(bailIfIEqualZero == 0)
return;
if(string.IsNullOrEmpty(shouldNeverBeEmpty))
return;
if(betterNotBeNull == null || betterNotBeNull.RunAwayIfTrue)
return;
//yadda
将其分解为一个函数,并将每个条件作为守卫子句:
int maybe_do_something(...) {
if(something != -1)
return 0;
if(somethingelse != -1)
return 0;
if(etc != -1)
return 0;
do_something();
return 1;
}
bool TeamAIsGoForLaunch = BobSaysGo && BillSaysGo;
bool TeamBIsGoForLaunch = JillSaysGo && JackSaysGo;
if (TeamAIsGoForLaunch && TeamBIsGoForLaunch && TeamC.isGoForLaunch())
将其重构为一个函数。
bool Check()
{
return (something == -1) && (somethingelse == -1) && (etc == -1);
}
或者,您可以在Check函数中构建更易读的代码/逻辑。
有很多处理这种情况的方法,但我挑选了一些。
首先,如果所有条件(if语句中的所有AND条件)+要执行的代码都是一次性的情况,则使用您已经拥有的代码。您可能想要做一些其他人已经建议的事情,重写以使用Guard-clause类型的代码。
换句话说,不要像这样:
if (a && b && c && d && ......)
DoSomething();
我可以帮您将以下内容翻译为中文:
...你可以将其改写为类似于以下内容:
if (!a) return;
if (!b) return;
if (!c) return;
if (!d) return;
if (!...) return;
DoSomething();
if (a && b && c && d && e && f && (h || i) && (j || k) || l)
if (CanAccessStream() && CanWriteToStream())
if (stream != null && buffer != null && inBuffer > 0 && stream.CanWrite)
stream.Write(buffer, 0, inBuffer);
else
throw new InvalidOperationException();
if (inBuffer > 0)
{
Debug.Assert(buffer != null);
WriteToStream(buffer, inBuffer);
}
...
private void WriteToStream(Byte[] buffer, Int32 count)
{
if (stream.CanWrite)
stream.Write(buffer, 0, count);
else
throw new InvalidOperationException();
}
if (new[] { something, somethingelse, ... }.All(x => x == -1)) {
}
*编辑:给数据添加一个额外的行:
var Data = new[] { something, somethingelse, ... };
if (Data.All(x => x == -1)) {
}
class mystate
{
int something;
int somethingelse;
int etc;
bool abletodostuff()
{
return (something == -1) && (somethingelse == -1) && (etc == -1);
}
}
看起来你有三个信息,这些信息共同代表了应用程序中的一个特定状态。与其在这三个状态上进行切换,为什么不创建一个封装它们的值呢?然后你可以在创建时使用对象层次结构或委托来绑定你想要运行的操作。
if(something != -1)
return MyEnum.Something;
if(somethingelse != -1)
return MyEnum.SomethingElse;
if(etc != -1)
return MyEnum.SomethingElseEntirely;
return MyEnum.None;