A colleague of mine and I were discussing good verb replacements for “GetOrCreate” data retrieval patterns, where the “Create” part is responsible for the instantiation of a new instance of something.  While the pattern I present here did not solve his particular problem, its at least worth sharing.  Its obvious, and probably in use commonly already, but I figure its worth noting.

Essentially the goal is to get away from a “GetOrCreate” master method call and just have two methods: Get(args) and Get(args, Foo default) and then leave the responsibility of default generation up to Foo.  This way there’s no unintended side effects and you don’t have to explicitly coalesce (though with this pattern you could as easily coalesce; strictly speaking it isn’t as “discoverable”)…

var foo = FooService.Get(23) ?? new Foo { ... };

So here’s the pattern defined in code:

public class Foo : ICloneable  
{
    private readonly static Foo __default = 
        new Foo { Bar = "...", Baz = Int32.MinValue };

    public string Bar { get; set; }
    public int Baz { get; set; }

    public static Foo Default()
    {
        return (Foo)__default.Clone();
    }

    public object Clone()
    {
        return new Foo { Bar = this.Bar, Baz = this.Baz };
    }
}

public class FooService  
{
    public Foo Get(int baz)
    {
        // retrieve from data store...
        return null;
    }

    public Foo Get(int baz, Func<Foo> @default)
    {
        return Get(baz) ?? @default.Invoke();
    }
}

You’ll see that any associated overhead with Clone only occurs if Get(baz) returns null.  I have specifically stepped around the common naming standard of “GetDefault()” for the function – its named like a property - because its intended usage is as follows:

var foo = new FooService().Get(12, Foo.Default);


An ICloneable reference type is pretty much required, though any immutable reference type could get by without cloning because any changes gives you a new copy of that type.