Returning dictionaries from methods

These methods have always bothered me. Without delving into the code, I have no idea which key or auxiliary value is supposed to be used in this dictionary. I did it myself a thousand times, I'm sure. But it always bothered me, because there is not much information in it.

IDictionary<int,HashSet<int>> GetExportedCharges() { ... } void GetVisitStatuses(IDictionary<int,HashSet<int>> exportedCharges) { ... } 

The presence of material in the dictionary makes sense, but all IDictionary methods have very abstract parameters. I assume that I can create a new class, implement IDictionary and rename all parameters. It just seems redundant. Makes a wish C # has a typdef directive.

How do you avoid returning dictionaries like this? Or do you avoid it at all?

+4
source share
2 answers

There is a very simple solution that you can find adequate:

 public class IdToSetOfWidgetNumbersMap : Dictionary<int,HashSet<int>> { } 

Benefits:

  • IdToSetOfWidgetNumbersMap at the method that returns IdToSetOfWidgetNumbersMap does not leave many questions open.
  • The class can be left completely empty or you can choose aliases for members exposed to Dictionary if you prefer

Inconvenience:

  • You need to create a do-nothing class for each type of dictionary.
+9
source

Personally, I do not avoid returning dictionaries.

I agree, having only the signature of the method, everything looks very vague. Therefore, my rule is to ALWAYS write comments in the style of "Dictionary (logical description of keys) - (logical description of values)." And hope that I won’t have to use something terrible like

 Dictionary<SomeType, <Dictionary<...>> 
0
source

All Articles