Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

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

Thanks

like image 570
CodingThunder Avatar asked Mar 17 '10 09:03

CodingThunder


People also ask

Does TypeScript have dictionary?

A collection of key and value pairs is called a dictionary in TypeScript. The dictionary is also referred as a map or a hash. A map can be created by using the type Map and the keyword new. We can store the collection of key value pairs inside a map by creating a map.

What is immutable Dictionary C#?

An immutable object is defined as an object that cannot be changed after it has been created.

How do you define a key value pair in TypeScript?

Use an index signature to define a key-value pair in TypeScript, e.g. const employee: { [key: string]: string | number } = {} . An index signature is used when we don't know all the names of a type's keys ahead of time, but we know the shape of their values. Copied!

How do I add a key value pair to a map in TypeScript?

Use the set() method to add a key/value pair to a Map , e.g. map. set('myKey', 'myValue') . The set() method adds or updates the element with the provided key and value and returns the Map object.


2 Answers

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.

like image 101
Tamás Szelei Avatar answered Oct 26 '22 21:10

Tamás Szelei


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.

like image 21
Seb Avatar answered Oct 26 '22 21:10

Seb