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

Leave a Comment