是深嵌套字典的反模式? [英] 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]
现在,我才知道这个代码是难以辨认,因为看定义语句,你不能告诉它正在使用的东西。唯一的好处,我可以在将其更改为词典<真正看到,字符串,PrerenderedTemplate>
是可读性。把每个嵌套到自己的类(如类PrerenderedTemplate {}类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.
- 那么,我的方法OK或者我应该多走一英里,并创建单独的类呢?
- 是不是还好介绍如何嵌套的
词典
工作在文档/注释 - 是否有处理这种嵌套?
- 请记住,这是一个私有成员,它并不需要为使用类人简单。
- 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.
更新
因此,通过礼启发,但无法使用元组,我决定创建自己的密钥生成器和执行他的模式是这样的:
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();
}
其中, FormatTools.LIST_ENTRY_DELIMITER
是Unicode私人使用字符 0xe04d
。
Where FormatTools.LIST_ENTRY_DELIMITER
is the Unicode Private Use Character 0xe04d
.
推荐答案
我提供了另一种选择:
Dictionary<Tuple<string, string, string>, string> pt;
访问字典:
pt[Tuple.Create("id","group","part")]
这篇关于是深嵌套字典的反模式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!