What's a good name for a method that gets or creates an object?
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. In this case a 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.
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.
How about Getsert
? from get
or insert
, since update
or insert
is Upsert
Though I haven't seen any popular frameworks use this term, but this conforms to the idea that @Jason Williams pointed out, that:
- it should be clear to the user that it would not just do a normal get
- You don't have to go to the documentation to see what it does
- Easy to pickup and intuitive? (I'm not sure)