Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"GetOrCreate" - does that idiom have an established name?

Ok, consider this common idiom that most of us have used many times (I assume):

class FooBarDictionary
{
    private Dictionary<String, FooBar> fooBars;

    ...

    FooBar GetOrCreate(String key)
    {
        FooBar fooBar;

        if (!fooBars.TryGetValue(key, out fooBar))
        {
            fooBar = new FooBar();
            fooBars.Add(key, fooBar);
        }

        return fooBar;
    }
}

Does it have any kind of established name?

(Yes, it's written in C#, but it can be "easily" transferred to C++. Hence that tag.)

like image 343
Johann Gerell Avatar asked Sep 22 '09 20:09

Johann Gerell


2 Answers

I always call such functions obtainSomething().

like image 72
alex tingle Avatar answered Sep 22 '22 20:09

alex tingle


It sort of depends why you're doing it - the idiom is one I've seen be called memoization, caching, initialisation on demand, create on first use. Normally I call the method "ensureFoo" rather than "GetOrCreate"

like image 25
Pete Kirkham Avatar answered Sep 23 '22 20:09

Pete Kirkham