Java – how to reduce the “cyclomatic complexity” of the following code
•
Java
I want to know how to reduce the cyclomatic complexity of the following code, if this is something I should worry about
Please refer to the method valuepojo Getsomething () (please don't worry about variable naming, this problem has been overridden for clarity)
public class ValuePojo { private ValueTypeEnum type; private BigDecimal value1; private BigDecimal value2; private BigDecimal value3; public ValuePojo() { super(); } /** * This method reports as "HIGH Cyclomatic Complexity" * * @return */ public BigDecimal getSomething() { if (this.type == null) { return null; } switch (this.type) { case TYPE_A: case TYPE_B: case TYPE_C: case TYPE_D: return this.value1; case TYPE_E: case TYPE_F: case TYPE_G: case TYPE_H: return this.value2; case TYPE_I: case TYPE_J: return this.value3; } return null; } }
Solution
The cyclomatic complexity is determined by the number of branches taken in the code If – else block, switch statement – both increase the cyclomatic complexity of the code and the number of test cases required to ensure proper code coverage
In order to reduce the complexity of the code, I suggest you delete the case statement without defined behavior and replace it with the default behavior in the switch statement
This is another question on stack overlays to solve this problem
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码