Primitive are not datatypes - or how to make me scratch my head

time to read 3 min | 533 words

This post hit a really sensitive point with me, Eber is showing some of the more complex forms of generics. Here is how he hold all the files in all the directories in all the computers

Dictionary<string, Dictionary<string, List<string>>> list = 
new Dictionary<string, Dictionary<string, List<string>>>();

I can't read code like this. I have a dictionary of a dictoary of a list. That is all fine and dandy, so far. The using code looks like this:

list[@\\Rhino][@"C:\Files"][5] 

The problem is that without knowing what this mean, I have no idea how to work with this. What is the first string, what is the second one, and what is the third one, for crying out loud?

Code like the above is opaque, is doesn't tell me what it is. A far better alternative would be something likes:

public class Domain
{
  public IDictionary<string,Computer> Computers { get; }
}

public class Computer
{
  public IDictionary<string, Directory> Directories { get; }
}

public class Directory
{
 public IList<string> Files { get; } 
}

This is a data structure that has a meaning. The client code looks like this:

domain.Computers[@"\\Rhino"].Directories[@"C:\Files"].Files[5]

Now I can read it without knowing having to know what the original author meant.

Yes, having generics can save us a bit of time in creating a new class, but you should ask yourself if this is worth losing the clarity of the code.