Search code examples
javaif-statementoptimizationswitch-statementcyclomatic-complexity

Java Code optimization : if else to resolve PMD complexity 24 to 0


I have string of array with size already defined and i have to iterate though this array and fill it with fields value of someObject I have . If i do this with if elseif elseif or switch case i get high complexity .. please kindly suggest proper way to do this

enter image description here


Solution

  • I would suggest you to use a map to keep the mapping like this:

      private static final Map<Integer, String> MAP_VALUES = new HashMap<Integer, String>();
    
      private static Map<Integer, String> getMapValues(Employe employe){
        if(MAP_VALUES.isEmpty()){
          MAP_VALUES.put(0, employe.getEmployeeI());
          MAP_VALUES.put(1, employe.getEmployeeLastName());
          MAP_VALUES.put(2, employe.getEmployeeDivision());
          ....
        }
        return MAP_VALUES;
      }
    
      public String getValueForEmploye(Employe employe){
        String[] value = ...;
        for(int i = 0; i < value.length; i++){
          value[i] = getMapValues(employe).get(i); 
        }
      }