降低Cyclomatic复杂性

时间:2014-02-05 15:28:45

标签: java complexity-theory

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

public class AnswerTypeEnumConverter implements CustomConverter {

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

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

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

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

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

以下是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; 
} 

我如何降低复杂性?

1 个答案:

答案 0 :(得分:4)

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

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

相关问题