I am working on some generalization of my code and I'm struggling with some cases which are irritating me because I think I'm having code duplicity.
1) I'm often working with some map<string, set<string>>
or map<string, set<SObject>>
.
Therefore, I wanted to generalize the following behaviour, which either creates the key in the map if it doesn't exist or update the set if the key exists.
Whether my set is a string or SObject I have the same code, replacing SObject by string. Therefore, I feel there is duplicity of code and I don't like it. Any idea how to solve that ?
My 2 methods:
public static map<string, set<string>> put_or_update_map(map<string, set<string>> original_map, string key, string value){
if(original_map.containskey(key)){
original_map.get(key).add(value);
}
else{
original_map.put(key, new set<string>{value});
}
return original_map;
}
public static map<string, set<SObject>> put_or_update_map(map<string, set<SObject>> original_map, string key, SObject value){
if(original_map.containskey(key)){
original_map.get(key).add(value);
}
else{
original_map.put(key, new set<SObject>{value});
}
return original_map;
}
2) With the SObject method above which is generalized for all SObject, I'm having troubles to call it.
For instance, I have a main method which does many stuffs and requires a map to be of <string, set<Opportunity>>
Therefore, my main method can be summarized like this, with the way I'd call the method described above as follows:
map<string, set<Opportunity>> my_map = map<string, set<Opportunity>>();
(.... create and do some stuff with my_map, requiring it to be of <string, set<Opportunity> ...)
for(Opportunity my_opp: all_opps){
attempt1: my_map = put_or_update_map(my_map, my_opp.field, my_opp); //error: invalid signature
attempt2: my_map = put_or_update_map(my_map, my_opp.field, (SObject) my_opp); //error: invalid signature
}
(.... do some other stuff with my_map, requiring it to be of <string, set<Opportunity> ...)
Therefore, how can I do to properly call this method generalized every time I need it ? Duplicating it for all my SObject doesn't have make sense to me... Should I convert all my stuff in my main method to work on a generalized SObject map, which is a bit of a pain ? For instance, fields for specific objects aren't accessible, i.e my_map.get('key')[0].Name can't be used for instance
Any help on this is greatly appreciated
Thanks
Set<SObject>
unless you are very familiar with the mechanics, to the point where you could explain them to a high schooler.