What's a good name for a method that gets or creates an object?

Solution 1:

In most cases a simple GetFoo suffices as the caller doesn't need to know that you are creating and caching it. That's what encapsulation is all about.

However, in some circumstances, creating is an expensive operation, so it's useful to know that you may be creating something on demand and in some cases it will be slow. In this case, a different naming convention makes it clearer to the caller. GetOrCreate() or Get(Options.CreateIfMissing) is a good hint to the caller.

(The behaviour should of course be noted in the documentation, but it's good to use a method name that reminds people about side effects while they are reading the code, without them having to bring up and read the documentation for every method that is called)

The sort of case I find this happening in most often is (for example) when finding a tree node (e.g. in an XML document) you might have CreateNode (to create a node without adding it to the tree) and AddNode (to add an existing node to the tree). In this case, an "Add a node if it doesn't already exist" needs to have a different, descriptive name, so I will use something like EnsureNodeExists to differentiate it and make the purpose clear.

Solution 2:

I know I'm very late at the question, but can I propose GrabFoo() as a convention for get-or-create-if-missing to differentiate it from GetFoo()?

Looking at the synonyms of Get, I see several suitable verbs, some already commonly used as method verbs. For example, Fetch already connotes fetching something from an external system. (e.g. database or network)

Grab seems like rarely used, and might be carrying an (albeit weak) semantic of I want you to get-or-create it, no matter what.