Feature to get or add value to an associative array.

Jonathan M Davis newsgroup.d at jmdavisprog.com
Fri Apr 20 02:12:37 UTC 2018


On Wednesday, April 18, 2018 17:19:45 Giles Bathgate via Digitalmars-d 
wrote:
> On Sunday, 15 April 2018 at 22:55:41 UTC, Giles Bathgate wrote:
> > Time for a bikeshed discussion...
>
> I have had some thoughts about the name and would like to share
> my idea.
>
> Firstly to summarise here are the names that have been
> found/discussed so far:
>
> C#                   : GetOrAdd
> Java                 : computeIfAbsent
> Python               : setdefault
> Rust                 : entry(key).or_insert_with
>
> Jordan Wilson        : getOrAdd, getOrSet
> User1234             : valueOrDefault
> Nicholas Wilson      : getOrInsert
> Steven Schveighoffer : getPtr, getRef, getInitialized
> Nick Treleaven       : slot
> MrSmith              : getOrCreate
>
> My latest idea is just a working title, but I think I prefer it
> to my original getOrAdd.
>
> Giles Bathgate       : require
>
> My thinking is that if you `require` there to be a value in the
> associative array, then you should have the ability to add one
> iff it doesn't exist. It name also has parallels with the term in
> other programming languages to require a module, meaning to
> import it if it hasn't already been loaded.

Out of all of those, I _really_ hope that you don't go with require. It
sounds like the sort of thing that you'd get in a library having to do with
unit testing or contracts and gives no indication whatsoever as to what it
does. The only one in that list that seems similarly opaque is slot. Those
names say nothing about either getting a value or adding / inserting one.
Every other name at least gives some clue as to what the function does.

If I were adding it, and we already had get, I would just make it an
optional argument to get, which wouldn't necessarily be clear about
inserting, but it would at least be clear about getting. However, since we
used overloaded operators, there's no get.

Another option would be getOrInit, though I agree that they're all kind of
ugly.

Either way, IMHO, getOrAdd is infinitely better than require.

- Jonathan M Davis



More information about the Digitalmars-d mailing list