开发者

Why are Dictionary<k,v>'s on interfaces a bad idea?

开发者 https://www.devze.com 2022-12-23 08:50 出处:网络
Why are Dictionary<k,v>开发者_开发问答\'s on interfaces a bad idea? ThanksBecause even if you make them readonly or const, that doesn\'t stop clients from modifying the contents of the dictiona

Why are Dictionary<k,v>开发者_开发问答's on interfaces a bad idea?

Thanks


Because even if you make them readonly or const, that doesn't stop clients from modifying the contents of the dictionary (without your provision). The same applies to arrays and lists on public interfaces.

To address this problem, you can either give a copy of the container to the client (as jk mentioned in his/her comment), or (would it be too expensive to copy the whole container) provide accessor methods to it like getItem and setItem. This way you keep control of the contents of the container.


If you need trigger actions when the dictionary is modified or restrain the access to it (forbid removal as an example) you have to provide in your interface methods that wrap the dictionary. Moreover, you'll gain flexibility if you want to replace the underlying container, in that case the dictionary.

The List<> has a nice feature : the AsReadOnly() method that returns a IList<> implementation that is read only.


Firstly, one should prefer to expose collections via their interface verses a concrete type as this helps avoiding exposing what sort of collection is being used to clients and gives the class writer (interface implementer) the freedom to utilize whatever collection best suites the given need/constraints. For example I can expose an IList from an interface and then as the implementer of a class that implements this interface I have the freedom to choose to use a sortedlist, bag, set or whatever collection best suites my needs.

Whether you should even expose a collection from an interface is debatable - if a List is exposed from an class and the class has strict rules governing whether you can add an item to the collection or not, what is stopping clients from manipulating the collection directly thus circumventing whatever logic there was. As opposed to this an AddItem method can guarantee that only correct items are added.

In the dictionary case you could expose the items as a IEnumerable<KeyValuePair<k,v>> and have a find method that will offer us the ability to find an item using regular dictionary searching mechanics. Alternatively you could expose it as IDictionary and then return a readonly dictionary implementation


Are you talking about exposing them as properties?

Because a method parameter of type IDictionary<k, v> to fill in some stuff can be very useful. Much like the AddRange(IEnumerable<T>) functions used in lists etc.

Note here, that I am using the interface IDictionary<k, v> and not the concrete class...

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号