The ensure concept is a programming practice that involves calling a method called EnsureXxx() before proceeding with your method call which deals with two main usages: security and performance.
Let’s start by discussing the security usage of the Ensure pattern. When you enter a piece of code that can be considered critical, one needs to make sure that the code can proceed safely. Thus, before executing any call that requires such safety, an Ensure method is called.
Typically, this method will check the state that the code is currently is running is valid (what defines valid is up to the program itself) and any properties are sanity checked. In case that the state or properties are invalid, the code will simply throw an exception and the execution is immediately stopped.
A typical signature of this method will not accept any parameter and return void, such as EnsureAccessToDatabase(). Such method will make sure that the application is in the correct state and any properties (such as the connection string) are properly set.
The second usage of the Ensure pattern is performance. Many times, creating new objects will create internal dependencies which may be expensive to create. Even worse, it might be the case that the code only makes use of a portion of such objects and ends up not using the expensive dependencies. In order to circumvent this, any performant code will delegate the creation of expensive objects until they are needed.
Let’s consider an example – let’s say we have an object that may require a database access if certain operations are executed. These certain operations would implement a call such as EnsureDatabaseConnection(), which would check if the database connection exists and opens it if it does not.
The second usage is a but obsolete nowadays though – given the introduction of the Lazy<T> class nowadays, it makes more sense to wrap your deferred instances in a Lazy<T> rather than in an Ensure method. The Lazy provides native multi-thread initialisation support which you will have to do manually in an ensure pattern.
In real world applications, I still use the security component of the pattern though; it’s a very clean way to do security and sanity checks in your code, without becoming bloated.
Until the next one!