When are associative arrays meant to throw a RangeError?

Ben Davis entheh at cantab.net
Sat Feb 18 14:00:47 PST 2012

On 18/02/2012 21:42, Ben Davis wrote:
> On 18/02/2012 20:54, Andrej Mitrovic wrote:
>> Returning the default initializer of the value type when the key
>> doesn't exist is a bad idea. Consider an integer, it's .init value is
>> 0. If I want to check if a value of a key is zero I could easily end
>> up with a silent bug:
>> int[string] aa;
>> aa["foobar"] = 5;
>> if (aa["fobar"] == 0) { } // will always be true
>> else { }
> Isn't this the kind of situation where you should be using an enum for
> the key type? Or indeed just creating a struct or a class to hold the
> values you need? Especially as remove() already gives you 'silent bugs'
> if the key is misspelled.

Oops, I mean misspelt :)

Another possible situation where you could already get a silent bug:

aa["foobar"] = 5;
aa["fobar"] = 6;
if (aa["foobar"]==5) {...}

Are you familiar with cases where an associative array is definitely the 
right tool for the job and you have a high risk of typos?

More information about the Digitalmars-d mailing list