views:

293

answers:

4

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.)

+3  A: 

Lazy Loading

http://en.wikipedia.org/wiki/Lazy%5Floading

jagprinderdeep
I'm not sure if this is exactly lazy-loading. Maybe smart lazy-loading.
Chris Dwyer
+4  A: 

I always call such functions obtainSomething().

alex tingle
+5  A: 

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"

Pete Kirkham
+1  A: 

I'm unsure of overall programming name for the high level pattern, but Perl has this wonderful behavior called Autovivification - namely, automatically creating hash (map) key with undefined value when you're querying the value of non-existing key in the hash.

DVK