Posts tagged with design-patterns

Changing type, the state pattern and LINQ to SQL

A question I see from time-to-time on LINQ to SQL relates to changing an entity’s class.

C# and VB.NET don’t allow a class to change its type at run-time and LINQ to SQL specifically doesn’t provide a mechanism for changing the underlying discriminator for this reason.

Discarding the current object and creating a new one is fraught with issues. What do we do about existing references, unsaved data, established associations and caches?

Start with an example

Consider an abstract Account class with SavingsAccount and CurrentAccount sub-classes. Bank accounts don’t change type once created (in my experience) so that’s good so far.

When we get into processing and validation logic its tempting to create ClosedAccount and OpenAccount classes but what happens during execution when closing an account?

A further consideration is how exactly ClosedAccount and OpenAccount fit into the hierarchy given the single-inheritance limitation of C# and VB.NET.

Enter the State Pattern

The ever-resourceful Gang of Four describe the State Pattern as:

Allow an object to alter its behavior when its internal state changes. The object will appear to change its class.

Taking the bank accounts example and applying the state pattern gives:

State Pattern class diagram

Account no longer needs to change type at run-time yet is still able to have clients call Validate and process Methods that end up in discrete methods as if inheritance had been used.

To achieve this we have:

  1. Created a State hierarchy that contains the logic we need to change at run-time
  2. Introduced a private member in Account that points to the current state instance
  3. Ensured the Account methods call the current state class via the private member

Because the state member is private and only accessed by Account itself we can happily create and dispose it as the conditions that affect the state change as much as we like without worrying about references to it.

This is best illustrated with code. Here rather than just calling the state’s validation logic there is a combination of core Account validation (balance), state validation (closed) and CheckingAccount validation (transaction limits):

public abstract class Account {
  private AccountState state;

  public virtual Status Validate(ITransaction tx) {
    Status result = state.Validate(tx);
    if (tx.Amount > Balance)
    return result;

public class SavingsAccount : Account {
  public override Status Validate(ITransaction tx) {
    Status result = base.Validate(tx);
    if (Transactions.Count > TransactionLimit)
    return result;

public class ClosedAccountState : AccountState {
  public override Status Validate(ITransaction tx) {
    return new Status(TransactionFailures.InvalidSourceAccount);

This is less complex than selectively replacing objects within our application at run-time and can bring additional benefits:

Like all guidance, patterns and principles do not blindly follow these guidelines or patterns but consider how it affects and fits with your application. For this particular example it not only solves the problem but helps maintainability – at least at this simple stage. Once Validation becomes sufficiently complex it would likely move out entirely into a new set of orchestrated classes just for that.

With LINQ to SQL (and other mappers)

Moving this example into an object-relational mapper requires two – not unexpected – database-mapped properties.

  1. The inheritance discriminator (Type)
  2. A state indicator (Active)

Sample class diagrams for accounts using state pattern

The only thing we need to ensure is the Account’s state member always refers to either a ClosedAccountState or OpenedAccountState depending upon the Active flag.

Given that LINQ to SQL code-generates the property for Active we could:

  1. Make Active private, wrap it in another property and set the state member when it changes and at initialization
  2. Make the state member a read-only property instead of an instance variable

The second works well here and given that AccountState is itself stateless (perhaps not the best choice of name) we can use a singleton to avoid multiple instances. The state instance variable in the Account class is replaced with:

private AccountState State {
  get {
    if (Active)
      return OpenAccountState.Instance;
      return ClosedAccountState.Instance;

The code continues to work and now changing the Active flag results in different behavior.

Best of all we still have the code in separate classes, no switch/case/if statements relating to validation or account types, a clean inheritance hierarchy and no running around trying to invalidate existing references.

Hitting the discriminator directly

There may be times when claims are made that a type has to change – perhaps data was entered incorrectly.

Before delving into the database or providing a tool to flip the underlying discriminator value consider:

  1. Does the new class interpret the same data in a different manner? Has a $1,000 credit limit just become a 1,000 transactions per-month limit?
  2. Would the object be valid in the new class? Did a ProposedCustomer just become ApprovedCustomer without a policy-enforced credit check?
  3. Are associations still honored? Are 300 unshipped orders for a GameProduct still honored for a BookProduct?

If in doubt don’t do it.

An inconsistent database bleeding through your application isn’t good for anyone and will take a lot longer to sort out than setting up a new entity.


ActiveRecord, the ugly design pattern

I first encountered the Gang of Four Design Patterns book back in 2001 when a friend lent me a copy. I didn’t immediately get it, most likely because my object oriented experience up to that point consisted primarily of small Delphi applications.

In the last few years I’ve been working on much larger systems and have come to appreciate design patterns enough to get my own copy and also to invest in Martin Fowler’s excellent Patterns of Enterprise Architecture which provides higher-level patterns aimed at large data-driven applications.

One of the design patterns presented, and indeed a core component of the Ruby on Rails framework, is that of the ActiveRecord which attempts to provide object-relational mapping.

It achieves this by specifying a single class per database table where instances of that class represent a row in the table – exposing a property for each field the row has in the database. Each ActiveRecord instance is therefore effectively a domain/business object.

So far so good but then the ActiveRecord pattern ignores the single responsibility principle by specifying that the object should also include a bunch of static methods for managing the table’s contents and retrieving instances.

What you end up with is one object with two distinct responsibilities separated by nothing but the static keyword. Static methods and fields can serve a useful purpose but dividing up responsibilities isn’t one of them and neither is to provide global-like access across your application (Singleton abusers take note).

I can think of at least two reasons why gluing two candidate objects into one physical one using the ‘static’ split causes ActiveRecord to suffer with problems:

Multiple connections

Sometimes an application requires connections to more than one database (e.g. reporting, aggregation, upgrading tools, per-user switching of database in a web application).

Static methods often rely on static fields which means you’re going to have trouble making the

data you’re going to have trouble making them behave like objects.

Inheritance mapping

There are three types of inheritance mapping techniques available.

  1. Concrete Table Inheritance – one table per concrete class containing columns for all fields of the class regardless of where they are declared
  2. Class Table Inheritance – one table per class in the hierarchy containing columns for fields of the class they are declared in only
  3. Single Table Inheritance – a single table for all classes in the hierarchy containing all columns for all possible sub-classes many of which will be null

Concrete Table is most likely where the tables created by the parent classes would have little or no value and Class Table where they do.

Single Table is what ActiveRecord implementations such as Ruby on Rails tend to use although quite how it works I’ve yet to discover… Does the parent class magically know enough about it’s child classes that it’s static methods can handle the update/select/delete? Can I ask the parent class for all objects and get a mixed collection back?


Fowler presents a number patterns as alternatives and many object-relational mapping (ORM) solutions including LINQ for SQL utilize them.


Patterns of Enterprise Application Architecture

While a big fan of patterns I found the original Gang of Four (GoF) book a little dry and so had left the pattern books alone until Martin Fowler’s Patterns of Enterprise Application Architecture (PEAA), got referenced so many times on-line I gave in and purchased a copy. I’m glad I did – even if the examples are mostly in Java with the very occasional one in C#.

The patterns in the original GoF were really about the interactions between the objects themselves and whilst PEAA has some object-to-object interactions it concentrates on problems encountered in “Enterprise Applications”. This includes database mappings, transactions, web pages and concurrency.

The first half of the book provides a readable narrative and discussion of the various patterns with recommendations for when to use each and when to avoid. Part two explains each pattern in detail providing an essential reference to the patterns themselves. This mix of half-narrative and half-reference works very well and is certainly something other programming books would do well to steal.

As somebody who has been writing ‘Enterprise’ applications for some time it is interesting to see many of the problems described in neutral terms as well as the road-not-travelled alternatives and a rationale for their existence. Even if you came up with something similar yourself (and I’m sure you’ll find a few) giving it a meaningful common name makes life easier when discussing the solution with others.

A fair chunk of the book covers object-relational mapping (ORM) and it addresses most all the issues including whether to go full domain model/data mapper, active record, record set as well as the more intricate issues such as lazy loading, locking, identity map and approaches for how many tables to use for a given object.

There are a couple of issues I have with some of the patterns that don’t seem to be addressed so I’ll throw them out here:

Identity Map

The identify map’s description is

“Ensures that each object gets loaded only once by keeping every loaded object in a map. Looks up objects using the map when referring to them.”

There are two problems here;

  1. Objects become stale as other users perform updates that your browser/user can never see until your session terminates and thus looses your map. “Log out to see changes” is not acceptable.
  2. Resource consumption is heavy as your identity map effectively holds every object loaded in memory regardless of whether it’s used any more. Those objects may reference other objects too – combine this with a web server and you’re looking at a recipe for disaster as resources dry up.

One approach would be use develop your map using some form of weak reference mechanism. This would mean that once your code looses the last reference the object will be eligible for garbage collection and subsequent reloading from the database. This effectively kills off the secondary role as a cache but better than a web site running out of memory showing lots of old data.


Martin puts forward his discussion of the Money class and while the rounding is useful in my experience a monetary amount and a currency isn’t much use without some way of getting an exchange rate to the base currency.

Lazy Load

The samples Martin provides here are not thread safe and you could easily find yourself with two different objects where you expect one. For a section on lazy loading for enterprise apps not having a double-check lock is a bit sloppy. To correct the sample on page 203 would be (I’ve also converted it to C# 2.0);

public List<Products> GetProducts() {
  if (products == null)
      if (products == null)
        products = Product.FindForSupplier(GetID());
  return products;

Overall a very good book – I really need to get to grips with the patterns Foreign Key Mapping and Class Table Inheritance now.