On Monday, 3 February 2014 at 10:32:58 UTC, Stanislav Blinov wrote:
On Monday, 3 February 2014 at 10:25:19 UTC, Chris wrote:

 T[T] attributes;
 // ....
 public auto getAttribute(T attr) {
     if (!(attr in attributes)) {
       return null; // Doesn't work for numbers!
     }
     return attributes[attr];
   }
}

One way would be to use std.typecons.Nullable(T) as a return type.

Thanks. I'll try this one.

Another would be to retink your design :) Note that for numbers, there's no distinct "does not exist" value (well, ok, we have NaN for floating point). Neither there is for structs. Generally such methods as your getAttribute either throw, or get a second optional parameter as hint on what to return when the element is not found in the dictionoary.

I'm reluctant to (over)use throw, because I think that throw should be the last resort when you cannot easily predict all the things that can go wrong. Simple requests should give simple answers. If the key doesn't exist it returns nothing.

The problem above only exists because of generic types, else it would be either 'null' or for numbers -1 or something. But if you have a good point I've overlooked, you can convince me of throw. No ideology :)

Reply via email to