i'm considering 3 approaches returning references internal dictionary instances (c#) in regards code safety , impact on code readability/visually project i'm working on.
i've narrowed down following 3 approaches, open better suggestions. prefer #3 best balance of safety without boiler plate.
1) use second readonlydictionary instance wrap internal dictionary, ever letting readonlydictionary escape class:
2) return dictionary instance ireadonlydictionary, recasting allow modified not safe option #1 or #3.
3) return dictionary.toimmutabledictionary() immutabledictionary when escapes containing class returned object immutable view of inner dictionary, although make new copy every call incurring higher cost, should fine small simple dictionaries (which mine are).
private readonly dictionary<string, string> innerdictionary = new dictionary<string, string>(); // required example #1 private readonly ireadonlydictionary<string, string> readonlyinnerdictionary; public exampleclass() { // required example #1 readonlyinnerdictionary = new readonlydictionary<string, string>(innerdictionary); } public ireadonlydictionary<string, string> getexampleone() { // requires second dictionary more boiler plate object being returned readonly return readonlyinnerdictionary; } public ireadonlydictionary<string, string> getexampletwo() { // requires innerdictionary defined dictionary (not idictionary) doesn't require second dictionary defined // less boiler plate, object returned re-cast it's mutable form meaning it's not mutation safe. return innerdictionary; } public immutabledictionary<string, string> getexamplethree() { // immutable object returned, new instance built every call; fortunately of dictionaries small (containing @ 9 keys) return innerdictionary.toimmutabledictionary(); }
option 1 way go. can recast readonlydictionary idictionary, throw exception when trying mutate:
void castingtest() { var dic1 = new dictionary<string, string>(); dic1.add("key", "value"); var dic2 = new readonlydictionary<string, string>(dic1); var casteddic = (idictionary<string, string>)dic2; casteddic.add("anotherkey", "another value"); //system.notsupportedexception, collection read }
the readonlydictionary doesn't create dictionary. points same reference of first one, encapsulating it. if do:
void addtest() { var dic1 = new dictionary<string, string>(); dic1.add("key", "value"); var dic2 = new readonlydictionary<string, string>(dic1); dic1.add("key2", "value2"); //now dic2 have 2 values too. }
never expose innerdictionary , you'll fine.
Comments
Post a Comment