圈复杂度的常见原因及其解决方案

发布于 2024-08-20 04:15:08 字数 92 浏览 2 评论 0原文

在工作中,我们正在研究导致高圈复杂度的常见问题。例如,拥有较大的 if-else 语句可能会导致较高的圈复杂度,但可以通过用多态性替换条件来解决。您还发现了哪些其他例子?

At work we are looking into common problems that lead to high cyclomatic complexity. For example, having a large if-else statement can lead to high cyclomatic complexity, but can be resolved by replacing conditionals with polymorphism. What other examples have you found?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

时间你老了 2024-08-27 04:15:08

请参阅 NDepend 的圈复杂度的定义

嵌套深度也是一个很好的代码指标。

圈复杂度是一种流行的程序软件度量,等于程序中可以做出的决策数量。具体来说,在 C# 中,方法的 CC 是 1 + {在方法主体中找到的以下表达式的数量}

:同时|对于 | foreach |案例 |默认|继续 |转到| && | || |抓住|三元运算符 ?: | ??

以下表达式不计入 CC 计算:

else |做|开关|尝试|使用 |扔|终于|返回 |对象创建|方法调用 |字段访问

适应 OO 世界,该度量在方法和类/结构上定义(作为其方法 CC 的总和)。请注意,在计算其外部方法的 CC 时,匿名方法的 CC 不被计算在内。

建议:CC 高于 15 的方法难以理解和维护。 CC 高于 30 的方法极其复杂,应拆分为更小的方法(除非它们是由工具自动生成的)。

See the NDepend's definition of Cyclomatic Complexity.

Nesting Depth is also a great code metric.

Cyclomatic complexity is a popular procedural software metric equal to the number of decisions that can be taken in a procedure. Concretely, in C# the CC of a method is 1 + {the number of following expressions found in the body of the method}:

if | while | for | foreach | case | default | continue | goto | && | || | catch | ternary operator ?: | ??

Following expressions are not counted for CC computation:

else | do | switch | try | using | throw | finally | return | object creation | method call | field access

Adapted to the OO world, this metric is defined both on methods and classes/structures (as the sum of its methods CC). Notice that the CC of an anonymous method is not counted when computing the CC of its outer method.

Recommendations: Methods where CC is higher than 15 are hard to understand and maintain. Methods where CC is higher than 30 are extremely complex and should be split in smaller methods (except if they are automatically generated by a tool).

丘比特射中我 2024-08-27 04:15:08

避免使用太多 if 的另一个例子是有限状态机的实现。因为事件会触发转换,所以条件以更清晰的方式隐含在这些改变系统状态的转换中。控制更容易。

给您留下一个提到它的一些好处的链接:

http://www.skorks.com/2011/09/why-developers-never-use-state-machines/

Another example to avoid using so many if´s, it's the implementation of a Finite State Machine. Because events fire transitions, so the conditionals are implicit in a clearer way with these transitions that changes the state of the System. The control is easier.

Leave you a link where mentions some of it´s benefits:

http://www.skorks.com/2011/09/why-developers-never-use-state-machines/

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文