Is there a better way to write the following code fragment?
I can't have more than 10 conditional statement in my method as it gives cyclomatic complexity.
private List<AutoDto> getFilteredAutoList()
{
List<AutoDto> autoList = getAutoListForCoverage();
List<AutoDto> filteredAutoList = new ArrayList<AutoDto>();
for(AutoDto auto : autoList)
{
if("FAQ025".equals((auto.getCarCode()))
||"FAQ025".equals((auto.getCarCode()))
||"QEF025".equals((auto.getCarCode()))
||"QEF037AB".equals((auto.getCarCode()))
||"FAQ037AB".equals((auto.getCarCode()))
||"FAQ045".equals((auto.getCarCode()))
||"QEF045".equals((auto.getCarCode()))
||"NBEF028".equals((auto.getCarCode()))
||"OPCF028".equals((auto.getCarCode()))
//20 more OR conditions
)
{
filteredAutoList.add(auto);
}
}
return filteredAutoList;
}
The following two approaches came to my mind:
Using
HashSet
private List<AutoDto> getFilteredAutoList() { List<AutoDto> autoList = getAutoListForCoverage(); List<AutoDto> filteredAutoList = new ArrayList<AutoDto>(); Set<String> carCodeSet = getCarCodeSet(); for(AutoDto auto : autoList) { if(carCodeSet.contains(auto.getCarCode())) { filteredAutoList.add(auto); } } return filteredAutoList; } private Set<String> getCarCodeSet() { Set<String> carCodeSet = new HashSet<String>(); carCodeSet.add("FAQ025"); carCodeSet.add("QEF025"); carCodeSet.add("QEF037AB"); carCodeSet.add("FAQ037AB"); carCodeSet.add("FAQ045"); carCodeSet.add("QEF045"); carCodeSet.add("NBEF028"); carCodeSet.add("OPCF028"); //20 more codes to be added return carCodeSet; }
Using
String
contains
methodprivate List<AutoDto> getFilteredAutoList1() { List<AutoDto> autoList = getAutoListForCoverage(); List<AutoDto> filteredAutoList = new ArrayList<AutoDto>(); String carCodeString = "FAQ025,QEF025,QEF037AB,FAQ037AB,FAQ045,QEF045,NBEF028,OPCF028"; for(AutoDto auto : autoList) { if(carCodeString.contains(auto.getCarCode())) { filteredAutoList.add(auto); } } return filteredAutoList; }
Which approach should I follow and why?
FAQ02
? That is contained inFAQ025,Q...
, but it shouldn't count. I would use a static array (define it at the top of the class) and check if the car code is in it. \$\endgroup\$