什么时候保留地图< Identifier,Object>.与Collection<标识符为字段的对象> [英] When do I keep a map<Identifier, Object> vs a Collection<Object with identifier as field>
问题描述
在设计程序时,我经常问自己一个问题,但我不确定如何回答.
There is one question that I often ask myself while designing a program, and I am never quite sure how to answer it.
假设我有一个具有多个字段的对象,其中有一个充当该特定对象的标识符.再说一遍,我需要在其他地方跟踪此类对象的列表.
Let's say I have an object with multiple fields, amongst which there is one serving as the identifier to that specific object. Let's also say that I need to keep track of a List of such objects somewhere else.
我现在有三个甚至可能更多的选择方法:
I now have three, and probably even more, options on how to go about it:
- 让我的对象包含其自己的标识符以及所有其他字段.现在,在需要的地方使用我的对象的简单数组(或任何简单的列表集合).当我正在寻找一个特定的对象时,我会遍历列表并检查标识符是否相等.
优点:1.每个对象实例的清晰度".2.?缺点:操纵这些对象的集合很烦人
Pros: 1. "Clarity" for each object instance. 2.? Cons: Manipulating a collection of these objects gets annoying
- 让我的对象包含其标识符旁边的所有字段.现在,我使用一个以标识符为键,对象为值的Map.当寻找一个特定的对象时,我只是在地图上查找标识符.
优点:易于查找和插入?缺点:对象实例本身不知道它是什么?
Pros: easy lookups and insertions,? Cons: object instance itself doesnt know what it is,?
- 两者的结合:使用以标识符为键的映射和以标识符为域的对象作为值.
优点:如上所述.缺点:对我来说似乎多余.
Pros: mentioned above. Cons: looks redundant to me.
什么情况需要什么?让我们使用标准的hello-world网络示例,例如聊天服务器:我将如何处理所在的多个组/渠道"人?那其他应用程序呢?
What situations would call for what? Let's use the standard hello-world example of networking for example, a chat server: how would I handle multiple "groups/channels" people are in? What about other applications?
推荐答案
两个准则可以回答这个问题:
Two guidelines may answer this question:
- 一个用例需要在键与值之间存在1:1关系的情况下进行查找,这意味着Map结构.
- OOP意味着与对象紧密相关以执行查找的键应该封装在该对象中.
关于冗余性问题,请考虑映射中的关键字不过是索引.索引在数据中和书籍中一样普遍.
Regarding the question of redundancy, consider the key in a map is nothing but an index. Indexes are as common in data as in books.
这篇关于什么时候保留地图< Identifier,Object>.与Collection<标识符为字段的对象>的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!