Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
305 views
in Technique[技术] by (71.8m points)

c# - Is a deep nested Dictionary an antipattern?

I have a structure that can be very easily represented using a three-deep nested dictionary, like so

private static Dictionary<string, Dictionary<string, Dictionary<string,string>>> PrerenderedTemplates;

Where the structure might be used something like this

PrerenderedTemplates[instanceID][templategroup][templatepart]

Now, I realise that this code is hard to read, because from looking at the definition statement, you can't tell what it's being used for. The only advantage I can really see in changing it to Dictionary<string, PrerenderedTemplate> is readability. Converting each nesting into its own class (e.g class PrerenderedTemplate{} class TemplateGroup{} class TemplatePart{}) would add many more lines of code for little (if any) computational advantage. As far as I can see.

  • So, is my approach "ok" or should I go the extra mile and create seperate classes?
  • Is it okay to cover how the nested Dictionary works in the documentation/comments
  • Is there a best practice for handling this sort of nesting?
  • Bear in mind, this is a private member, it doesn't need to be straightforward for people using the class.

Update

So, inspired by Reza, but unable to use Tuples, I decided to create my own key generator and implement his pattern like this:

private Dictionary<string, string> PrerenderedTemplates;
private string GetPrerenderedTemplateKey(string InstanceId, string FeatureId, string OptionId)
{
    return new StringBuilder(instanceId)
    .Append(FormatTools.LIST_ENTRY_DELIMITER)
    .Append(templategroup)
    .Append(FormatTools.LIST_ENTRY_DELIMITER)
    .Append(templatepart).ToString();
}

Where FormatTools.LIST_ENTRY_DELIMITER is the Unicode Private Use Character 0xe04d.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I offer another choice:

Dictionary<Tuple<string, string, string>, string> pt;

Access to dictionary:

pt[Tuple.Create("id","group","part")]

UPDATE:

Value Tuples introduced in C# 7 is most eye-catching:

Dictionary<(string id, string group, string part), string> pt;

Access to dictionary:

pt[("id", "group", "part")]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...