java 认知复杂度及其对代码的影响
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/46673399/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Cognitive Complexity and its effect on the code
提问by vmorusu
W.r.t to one of the java projects, we recently started using SonarLint. Output of the code analysis shows too many critical code smell alerts.
对于其中一个 Java 项目,我们最近开始使用 SonarLint。代码分析的输出显示了过多的关键代码异味警报。
Critical code smell: Refactor this method to reduce its Cognitive Complexity.
I have heard about Cyclomatic Complexity but not about Cognitive Complexity. My questions to the group:
我听说过圈复杂度,但没有听说过认知复杂度。我对小组的问题:
- Is Cognitive Complexity an industry standard?
- Impacts of Cognitive Complexity on code apart from readability and maintainability.
- Does Cognitive Complexity apply only to methods or any other parts of code?
- Any specific criteria on which Cognitive Complexity depends on?
- Best practices to improve Cognitive Complexity of a code.
- 认知复杂性是行业标准吗?
- 除了可读性和可维护性之外,认知复杂性对代码的影响。
- 认知复杂性是否仅适用于方法或代码的任何其他部分?
- 认知复杂性所依赖的任何特定标准?
- 提高代码认知复杂性的最佳实践。
I have gone through this linkbut could not get answers to all my questions.
我已经浏览了此链接,但无法获得所有问题的答案。
Thanks in advance.
提前致谢。
回答by Sorin
Humans can easily keep in mind about 7 entities +/- 2(wikipedia). When somebody needs to read the code they may run into this limit. Sometimes there are too many local variables to keep track of, or too many if/for statements. In all cases it makes it harder to understand what the code is supposed to do because it's hard to keep a mental picture of the algorithm.
人类可以轻松记住大约 7 个实体 +/- 2(维基百科)。当有人需要阅读代码时,他们可能会遇到这个限制。有时需要跟踪的局部变量太多,或者 if/for 语句太多。在所有情况下,都很难理解代码应该做什么,因为很难在脑海中保留算法的图景。
Industry standard: No.
行业标准:无
Readability and maintainability: It's easier to debug/improve code that is simple and easy to read.
可读性和可维护性:更容易调试/改进简单易读的代码。
Applies on methods or other parts: Everything that some human might want to understand. If you try to explain your design and I need to keep track of 20+ classes, I'll be lost. If I need to work quickly with your interface but I need to remember 10 bits of state, I won't be able to.
适用于方法或其他部分:某些人可能想了解的一切。如果你试图解释你的设计,而我需要跟踪 20 多个类,我会迷路的。如果我需要快速处理你的界面,但我需要记住 10 位状态,我将无法做到。
Any specific criteria it depends on: The amount of things one needs to remember to understand the code.
它取决于的任何特定标准: 理解代码需要记住的事情的数量。
Best practices: Make more and better defined functions. Extract related concepts into groups/packages. Reduce the number of nesting levels in the code (if you read a nested code you need to remember the condition that got you there). Reduce the number of in use variables at any one point (works great with extracting functions).
最佳实践:创建更多更好定义的功能。将相关概念提取到组/包中。减少代码中的嵌套级别数(如果您阅读嵌套代码,您需要记住使您到达那里的条件)。在任何一点减少使用变量的数量(与提取函数一起使用效果很好)。