Sign up ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free.

I use a pattern that I call "ensure" extensively in my repository layer. In short, it does the following when I call an Ensure(...) method:

  1. It uses the arguments in the method to attempt to populate an entity of a specified type (ultimately from the database),
  2. If it finds one then it returns it; f it does not, it saves the entity to the database and return it.

So, my Ensure method ensures that there is always a populated entity with specified properties, irrespective of whether one existed before the call was made.

Is there already a more commonly known name for this pattern?

share|improve this question
Doesn't this pattern break the query / command separation principle ( – Giorgio Dec 14 '13 at 9:30
Good question - however, under the hood it does two separate calls. So, it doesn't violate the principle. This kind of pattern is used quite a lot in well written import routines, for example. It's a shame that I cannot find a name for it. – Carnotaurus Dec 14 '13 at 10:03
Are assertions what you look for? – JensG Dec 14 '13 at 10:43
We tend to call it GetOrCreate. @JensG I don't think assertions are going to help here. I think the description makes it pretty clear that he wants to return a specific instance - and if it doesn't exist already - create it first. A sort of lazy instantiation, but in this case the database plays a role in it as well. – Marjan Venema Dec 14 '13 at 10:54
Hey @Carnotaurus, why did you delete this? Don't worry about the downvote, it's a decent question. You can't reply to this comment while the question is deleted, if you want to further discuss the question I'll be in our chat room. In any case, look up lazy initialization, it's a technique that's very close to what you are doing. – Yannis Dec 14 '13 at 12:30

1 Answer 1

I believe your name is correct, Microsoft has a method called .GetOrCreate(int id, ...) in the LifetimeContext class located at System.Composition.Hosting namespace (.NET 4.5) that does exactly this. See here

But, my opinion is that you are in fact implementing a different version of a Multiton Pattern (see here) the only difference from the normal implementation is that instead of having a cache of entities, you are going to the database to check for the "instances", so you could consider changing your method to .GetInstance(int id) or even .GetInstance<T> in a generic repository.

But your name is also correct, like i said, it´s a different approach.

share|improve this answer
+1 for multiton, might also consider this a form of memoization – jk. Jan 22 '14 at 16:20

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.