Java 降低圈复杂度

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21581370/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 09:29:51  来源:igfitidea点击:

Reducing the Cyclomatic Complexity

javacomplexity-theory

提问by Abhishek

How can I reduce the cyclomatic complexity of the following code

如何降低以下代码的圈复杂度

public class AnswerTypeEnumConverter implements CustomConverter {

    public Object convert(Object destination, Object source, Class destinationClass, Class sourceClass)
    ...

the method convert()is from the interface CustomConverterwhich is a predefined interface in my project and is provided as a jar, so I can't change the signature of the convert()method, which is

该方法convert()来自接口CustomConverter,它是我项目中的预定义接口并作为 jar 提供,因此我无法更改该convert()方法的签名,即

Object convert(Object existingDestinationFieldValue, Object sourceFieldValue, Class<?> destinationClass, Class<?> sourceClass);

I am using SONAR 3.6 and it is showing error as:

我正在使用 SONAR 3.6,它显示的错误为:

The Cyclomatic Complexity of this method is 15 which is greater than 10 authorized.

Here is the code for the convertmethod

这是该convert方法的代码

public Object convert(Object destination, Object source, Class<?> destinationClass, Class<?> sourceClass) { 
    Object destinationValue = destination; 
    if (source == null) { 
        LOGGER.info("APPLICATION OBJECT IS NULL CONVERSION STOPPED AND RETURNING NULL");
        return null; 
    } 
    if (destinationValue == null) { 
        destinationValue = new KYExchangeTransfer(); 
    } 
    destinationValue = setRequest(((Application) source), ((KYExchangeTransfer) destinationValue)); 
    return destinationValue; 
} 

How can i reduce the complexity?

我怎样才能降低复杂性?

回答by zimi

You should remove if, else if, else, switch, while, etc. (every flow instruction) and move them to another method or use appropriate design pattern.

您应该删除 if、else if、else、switch、while 等(每个流程指令)并将它们移动到另一种方法或使用适当的设计模式。

For example you should change long if else chain into polymorphism

例如,您应该将 long if else 链更改为多态