【发布时间】:2015-04-23 20:38:59
【问题描述】:
我有一个 (C#) 函数,它检查四组条件并返回一个布尔值。如果其中任何一个为真,则返回true。我确信我可以简化逻辑,但我希望它具有相当的可读性。
Visual Studios 中的 CodeMaid 扩展,告诉我函数的圈复杂度是 12。我 looked it up 圈复杂度是
通过源代码的独立路径数
我不明白为什么它是 12。我可以想到两种方式,圈复杂度应该是 2,因为它总是经过相同的路径,但可以返回 true 或 false。或者可以理解它是否是 16,因为最后在一起的四个布尔值 or 可以分别为真或假,2*2*2*2 = 16。
谁能告诉我为什么是 12?甚至可以显示一个图表,以便我可以可视化不同的路径?
public bool FitsCheckBoxCriteria(TaskClass tasks)
{
// note: bool == true/false comparisons mean you don't have to cast 'bool?' as bool
// if neither checkboxes are checked, show everything
bool showEverything = NoShutDownRequiredCheckBox.IsChecked == false &&
ActiveRequiredCheckBox.IsChecked == false;
// if both are checked, only show active non-shutdown tasks
bool showActiveNonShutdown = ActiveRequiredCheckBox.IsChecked == true &&
tasks.Active == "YES" &&
NoShutDownRequiredCheckBox.IsChecked == true &&
tasks.ShutdownRequired == "NO";
// if active is checked but shudown isn't, display all active
bool showActive = ActiveRequiredCheckBox.IsChecked == true &&
tasks.Active == "YES" &&
NoShutDownRequiredCheckBox.IsChecked == false;
// if non-shutdown is checked but active isn't, display all non-shutdown tasks
bool showNonShutdown = NoShutDownRequiredCheckBox.IsChecked == true &&
tasks.ShutdownRequired == "NO" &&
ActiveRequiredCheckBox.IsChecked == false;
return showEverything || showActiveNonShutdown || showActive || showNonShutdown;
}
提前致谢。
编辑:
我把它改成了这个。为复选框条件分配局部变量没有任何效果,但是从“YES”/“NO”创建布尔值将复杂度提高到 14,我想我理解。
public bool FitsCheckBoxCriteria(LubeTask tasks)
{
bool noShutdownReqChecked = (bool)NoShutDownRequiredCheckBox.IsChecked;
bool activeChecked = (bool)ActiveRequiredCheckBox.IsChecked;
bool active = tasks.Active == "YES" ? true : false;
bool shutdownReq = tasks.ShutdownRequired == "YES" ? true : false;
// if neither checkboxes are checked, show everything
bool showEverything = !noShutdownReqChecked && !activeChecked;
// if both are checked, only show activeChecked non-shutdown tasks
bool showActiveNonShutdown = activeChecked && noShutdownReqChecked && active && !shutdownReq;
// if activeChecked is checked but shudown isn't, display all activeChecked
bool showActive = activeChecked && !noShutdownReqChecked && active;
// if non-shutdown is chceked but activeChecked isn't, display all non-shutdown tasks
bool showNonShutdown = noShutdownReqChecked && !activeChecked && !shutdownReq;
return showEverything || showActiveNonShutdown || showActive || showNonShutdown;
}
【问题讨论】:
-
只是好奇,如果删除所有
== true语句并将== false更改为!,复杂性会发生什么?它们是多余的 -
@moarboilerplate 我知道它们是多余的。只是这些类型是
bool?而不是bool,所以为了便于阅读,我没有将它们全部转换,而是进行了比较。 msdn.microsoft.com/en-us/library/bb384091.aspx -
是的,但它对复杂性有什么影响?另外,如果您有兴趣对此进行优化,我会使用标志枚举和按位运算来为每个位设置权限。
-
(虽然这确实消除了布尔值的可空方面)
-
嗯,我摆脱了比较并做了演员表,但并没有改变复杂性。不过那会很整洁。
标签: c# complexity-theory cyclomatic-complexity