Need your help because I'm overthinking a bit. :P I'm doing a development in apex where we build a Map based on certain keys. Those keys are a mix of multiple variables and so when building a map we have something like:
for(rule){
key = String.isBlank(rule.CompanyRisk) ? '' : rule.CompanyRisk;
key += String.isBlank(rule.PriceType) ? '' : rule.PriceType;
key += String.isBlank(rule.Product) ? '' : rule.Product;
key += String.isBlank(rule.CompanySize) ? '' : rule.CompanySize;
//..
map.put(Key, rule.Value);
}
return map;
//and later to get the correct value
for(offerRecord){
String accRisk = offerRecord.CompanyRisk;
String price = offerRecord.PriceType;
String product= offerRecord.Product;
String accSize = offerRecord.CompanySize;
if(map.contains(accRisk + price + product + accSize)){
key = accRisk + price + product + accSize;
}else if(map.contains( accRisk + price + product + '')){
key = accRisk + price + product + '';
}else if(map.contains(accRisk + price + '' + accSize)){
key = accRisk + price + '' + accSize,
}else if.. //16 conditions now (4 variables as optional)
}
return map.get(key);
Issue: Some fields on the key are optional and that happens so the users dont need to create all the rules for all the combinatorions. and when those optional fields are empty/null it's because it applies for all values of the field.
Example: We can have a rule as (LowRisk + Indexed + Computer + Small) with Value=4 and a rule for (Low + Indexed + Computer + '' ) with Value=5 , meaning if the company is small applies the 1st rule but if it it's medium/big/top it applies the one without. Same for the other fields. I can have just one saying (HighRisk + + +) with a value of 0 without the need of specifying all the other criteriums and it applies for all of them.
Because we need to always checking first rules/keys with the optional fields filled, it will become a mess due to a lot of if else. The conditions are like (ABCD, ABC, ABD, AB, ACD, AC, AD, A, BCD, BC, BD, B, CD, C, D ,'' )
Is there any better solution that could improve this?
I was trying now building some Wrapper class that would return a List for the all combinations and then have a specific method getRuleForRecord() which based on the List (ordered) creates a key from the values of record and checks if map has that key. Not a much prettier aproach. The worst now is building the listOfCombinations on the order I want
List<String> keyList = singleton.listOfCombinations;
for (String fieldList : keyList) {
String mapKey = '';
for (String field : fieldList.split('_')) {
mapKey += recordToGetInfoFrom.get(field);
}
if (singleton.ruleMap.containsKey(mapKey)) {
return singleton.remRules.get(mapKey);
}
}