Click here to Skip to main content
Email Password   helpLost your password?

Introduction

The Essence Pattern provides a way to enforce users of an object to enter valid properties for that object. A full description of the pattern can be found in the original paper here (PDF). In this article, I shall provide a C# implementation of this pattern.

Background

If you are providing an external interface to your code either as an API or because your code forms a tier in an n-tier system, then the Essence Pattern can be used to force other programmers to put valid, required fields into an object before they start using that object. One common situation where this is required is for key fields to be saved to a database. The user of the object must not attempt to save that object to the database without the key properties, or the database will complain.

Of course, you could simply provide just one constructor that forces the programmer to enter all the required properties. In the simple case this is perfectly acceptable. However, if you are exposing an external interface, you may also want it to be COM wrappable. In this case, you can only have one, parameterless constructor which disallows that particular strategy. Also, what if there are a lot of required parameters, some of which need to be calculated or read from a data source? Are you going to make the user of your object store all these in local variables before they can construct your object?

The Example Code

The code sample with this article shows a very simple implementation of the Essence Pattern for a small class representing a contact. The Contact class has 5 properties, three of which are required (FirstName, LastName and Email), and two of which are optional (PhoneNumber and PostalAddress ).

The first thing we do is create the ContactEssence class as an internal class of the Contact class. The ContactEssence contains only the required properties for the contact (FirstName, LastName and Email), and allows read and write access to them all.

One of the two important methods of the ContaceEssence is the Validate method (shown below). This method essentially checks that all the required parameters are present and correct. Only when the Validate method returns true can the class advance to the next stage.

// Validates the essence fields.

private bool Validate()
{

  // Check we have a firstname

  if (mFirstName.Length == 0)
    return false;

  // ... and a last name

  if (mLastName.Length == 0)
    return false;

  // Check email exists and if it does, then check it's valid.

  if (mEmail.Length == 0)
    return false;
  else
  {
    // Use a regular expression to match an email address.

    System.Text.RegularExpressions.Regex emailReg = 
      new System.Text.RegularExpressions.Regex(
      @"^[\w-]+(?:\.[\w-]+)*@(?:[\w-]+\.)+[a-zA-Z]{2,7}$", 
      System.Text.RegularExpressions.RegexOptions.CultureInvariant);
    System.Text.RegularExpressions.MatchCollection results = 
      emailReg.Matches(mEmail, 0);

    // If we didn't get a mtach, fail the validation

    if (results.Count == 0)
      return false;
  }

  // Getting this far means validation is good

  return true;

}

The next stage is the creation of the real Contact class, which is done through a call to the ContactEssence.CreateContact method.

/// <summary>

/// Creates a <c>Contact</c> instance based on this essence.

/// </summary>

/// <returns>A new <c>Contact</c> 

/// if this <c>ContactEssence</c> is valid, 

/// otherwise a <c>null</c> reference.</returns>

public Contact CreateContact()
{
  if (this.Validate() == true)
    return new Contact(this);
    
  return null;
}

As you can see, if the ContactEssence is validated correctly, a Contact is returned.

The final part of the puzzle is the Contact class itself. The first area to look at are the constructors:

 // Private constructor can only be accessed by internal classes.

private Contact(ContactEssence xEssence) 
{
  // Copy required, immutable properties from essence

  mEmail = xEssence.Email;
  mFirstName = xEssence.FirstName;
  mLastName = xEssence.LastName; 
}

 // We make the default constructor private and mark it as obsolete.

[System.Obsolete(
 "Default constructor not valid -- use " + 
 "ContactEssence to create the Contace object", true)]
private Contact()
{
}

Both constructors are private. ContactEssence is an internal class to the Contact, so it has access to the private constructors. The second constructor is marked with the obsolete attribute simply to prevent its use at all. This means that the Contact class can only be created by the ContactEssence class.

When the Contact is created from the ContactEssence, it simply copies all the required fields. Additional (optional) fields are left in their original initialised state.

Finally, in the Contact class, the required fields are exposed as read-only properties, while the optional fields are read-write. This means that once the required fields are created, they cannot be changed.

So how do we use the Contact class?

The example code shows the role of the ContactEssence and the validation of required Contact properties:

// Cannot create contact directly this line 

// of code will create an error

//Essence.Contact c = new Contact(new Contact.ContactEssence());


// Create the essence

Contact.ContactEssence essence = new Contact.ContactEssence();

// Add the first required field

essence.Email = "me@mydomain.com";

// Cannot create Contact yet ...

Contact invalidContact = essence.CreateContact();
if (invalidContact == null)
  Console.WriteLine("Created NULL contact!");


// Fill in the rest of the required fields

essence.FirstName = "Dermot";
essence.LastName = "Gubbins";

// Try creating contact again

Contact validContact = essence.CreateContact();
if(validContact == null)
  Console.WriteLine("Oops! This should be valid!");
else
{
  // Add a phone number (optional)

  // but not an address.

  validContact.PhoneNumber = "(+44) 444 444";

  // Display the valid contact.

  Console.WriteLine("\nContact Created ...\n");
  Console.WriteLine(validContact.ToString());

}


Points of Interest

As explained in the original paper the Essence Pattern can be used in object creational patterns to create multiple valid classes by changing one or more of the required fields and then creating a new instance of the main class. Additionally, the Essence can also act as a builder class.

You must Sign In to use this message board.
 
 
Per page   
 FirstPrevNext
GeneralDo you see this as different from the Memento pattern?
panmanphil
7:25 23 Jun '04  
You have a nice example for c# coders, but it seems that the pattern was already named Wink .

Gang of four - Memento


Philip Nelson
GeneralRe: Do you see this as different from the Memento pattern?
Dr Herbie
22:38 23 Jun '04  
panmanphil wrote: Gang of four - Memento
No. The intent of these patterns is completely different.

Memento exists to store data in a decoupled way and has nothing to do with validation.

Essence has nothing to do with decoupling data storage and everything to do with validation.


It may be that the implementation of the Essence given in this article is similar to a Memento implementation, but there are different ways to implement it.

Did you read the original paper completely?

Dr Herbie
Remember, half the people out there have below average IQs.
GeneralRe: Do you see this as different from the Memento pattern?
panmanphil
5:58 24 Jun '04  
Yup, my bad. I had read the whole paper when the article first came out, but remembered the pattern yesterday while looking at ways to avoid using Flyweight when buiding objects from values in collections.

Right, memento has nothing to do with validation. The example does look like Memento because at first glance, it looked like all the fields of the target are covered in the Essence.

Have you found the pattern useful? How would Essence support the idea of changing a property protected by the essence? For example, once one of your contacts is created, you retrieve the *target* from persistence. While it could make perfect sense to enforce that a certain set of properties are protected this way in one use case, in another, completely different rules may apply. In your example, say the initial contact was created by an end user self registering on a web site. Later, the proprieters of the web site determine that the last name has changed because the woman got married. Multiple versions of Essences? A factory for Essences?

More and more it seems like we are forced to have a brainless persistent class that is augmented by use case specific strategies and constructed by builders. Hmmm, separation of data and method Wink


Philip Nelson
GeneralRe: Do you see this as different from the Memento pattern?
Dr Herbie
11:42 24 Jun '04  

I have found the Essence pattern useful in applications where objects represent rows in database tables: if forces the creation of new objects with all the key fields specified.
As for other forms of persistence, I form my code so that only valid (essence-created) objects can be persisted -- therefore when you 'hydrate' an instance, it is guaranteed to already have the key fields set without having to use the essence.

Once the object is initially created, the role of the Essence is over. I would therefore class the Essence as a purely creational pattern.

In my sample I made all the key fields immutable once set (becuase I'm used to databases). There is no reason why property mutators cannot be provided for these properties once the target class has been created. As long as there is logic to validate changes once the instance exists.
In databases, changing a primary key field means that a whole new data entity has been created. You would have to design you objects so that they could cope with such changes without invalidating the database structure (e.g. use an auto field as the primary key, but use the Essence pattern to ensure that a minimum amount of data is provided for every new database entry).

As for brainless persistence classes -- that's exactly what I use : Fowler's Data Transfer Object pattern and a generic persistence framework is something that I have been thinking of writing an article on, but it'll need a lot of planning (and permission from by boss).
Big Grin

Dr Herbie
Remember, half the people out there have below average IQs.
GeneralRe: Do you see this as different from the Memento pattern?
angrylala
20:34 15 Mar '07  
You guys should look at CSLA,
the validation framework supports dynamic detection of broken rules, etc on a property level and also on an object level.

GeneralMore like builder patther, Haha
Holy Joe
18:38 18 Jun '04  
I've a case: i have a class that must have a default public constructor(may be in COM+ use JustInTimeActivation and ObjectPooling attribute), but
i must control the construction process of it.
The essence pattern you introduced that has no way to do, Haha. I've a pattern can solve it, do you want to know it? haha

GeneralMore like builder patther, Haha
Holy Joe
18:32 18 Jun '04  
I've a case: i have a class that must have a default public constructor(may be in COM+ use JustInTimeActivation and ObjectPooling attribute), but
i must control that the construction process of it.
The essence pattern you introduced that has no way to do, Haha. I've a pattern can solve it, do you want to know it? haha

GeneralRe: More like builder patther, Haha
Dr Herbie
0:11 21 Jun '04  
Hi,
Yes, I'd like to know your pattern. If it's useful, why don't you write an article on it?


Dr Herbie
Remember, half the people out there have below average IQs.
GeneralEase of understanding
Clako08
22:56 17 Jun '04  
Even though the concept is appearent, perception would be greatly improved if you supplied the code for the "ContractEssence" class as well...


GeneralDon't need the defautl constructor
dgk
13:27 9 Jun '04  
C# only produces a default constructor if no other constructor exists for the class.. so you shouldn't need to have private Contact().

Derek Kowald
dkowald@bigpond.net.au
GeneralRe: Don't need the defautl constructor
Dr Herbie
22:44 9 Jun '04  

Thanks for the info, I didn't know that (obviously). Just goes to show that nobody knows everything Smile .



Dr Herbie
Remember, half the people out there have below average IQs.


Last Updated 9 Jun 2004 | Advertise | Privacy | Terms of Use | Copyright © CodeProject, 1999-2010