2

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 CustomConverter which 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

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

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

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

Here is the code for the convert method

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?

Ian McLaird
  • 5,507
  • 2
  • 22
  • 31
Abhishek
  • 55
  • 2
  • 2
  • 8

1 Answers1

4

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

For example you should change long if else chain into polymorphism

zimi
  • 1,586
  • 12
  • 27
  • There are 3 if statments in my code for the convert() and each have diffrent return types .... Is it feasible and correct to write a separate method for each of these ..... i tried putting these all if's in a separate method but result given was same by soanr ... Thanks in advance so what should i do .... – Abhishek Feb 06 '14 at 05:08
  • You're talking about 3 if statements but in code above I see only 2 if statements. Code which you're showing doesn't have so big cyclomatic complexity. You're doing something wrong. Maybe you're looking at wrong method somehow if changes in code make no diffrence in cyclomatic complexity. Double check everything what is needed. – zimi Feb 06 '14 at 06:41