Showing posts with label design patterns. Show all posts
Showing posts with label design patterns. Show all posts

Monday, March 15, 2010

Design Patterns – State Pattern

The State design pattern is a behavioural pattern. The behaviour of object changes accordingly to its internal state. Instead of implementing if-then-else like structure inside the object to switch the behaviour, we move the logic to property "State" which has method Handle() and call this method. We change the behaviour of the object as we just switch the value of the "State" property.

The class which behaviour will change accordingly to its state is named Context. The Context class contains property State which is of type that implements common IState interface.

We have different implementations of IState - StateOne, StateTwo etc. We assign new IState object to the property "State" of the Context object and the behaviour of the Context object changes.


Traffic Light



Imagine we are going to implement traffic light. Accordingly to Wikipedia we have three possible lights: red; amber and green. The traffic light cycle may vary, but we are going to implement 3-way traffic light cycle.


  • Red light - Means prohibits the traffic from proceeding.

  • Green light - Then follows the green light that allows to proceed.

  • Yellow light - Next is yellow light denoting if safe to, prepare to stop.



We will use the State pattern to implement a traffic light. The traffic light (TrafficLight) object is the context object. The traffic light has public properties for the color of the light currently turned on, it knows for how long this light should stay, and knows light of which color will follow after that. But setting these properties is done by State object.

We have 3 different states for the three traffic light colors. All they have method Handle() which is invoked by the TrafficLight object.


IState interface



All the concrete State classes have to implement interface ITrafficLightState. The concrete traffic light state handles request from the Context object and thereof the behaviour of the Context object changes.


interface ITrafficLightState
{
void Handle(TrafficLight trafficLight);
}


State implementations



For the different traffic light colors we implement three different State objects. All they implement interface ITrafficLightState:


// State "Red Light"
class RedLightState : ITrafficLightState
{
public void Handle(TrafficLight trafficLight)
{
trafficLight.Color = "Red"; // Switch the traffic light color
trafficLight.Pause = 5; // For 5 seconds
trafficLight.NextState = new GreenLightState(); // Then green light follows
}
}

// State "Amber Light"
class AmberLightState : ITrafficLightState
{
public void Handle(TrafficLight trafficLight)
{
trafficLight.Color = "Amber"; // Switch the traffic light color
trafficLight.Pause = 2; // For 2 seconds
trafficLight.NextState = new RedLightState(); // Then red light follows
}
}

// State "Green Light"
class GreenLightState : ITrafficLightState
{
public void Handle(TrafficLight trafficLight)
{
trafficLight.Color = "Green"; // Switch the traffic light color
trafficLight.Pause = 5; // For 5 seconds
trafficLight.NextState = new AmberLightState(); // Then Amber light follows
}
}



TrafficLight context object



How we are ready to implement the TrafficLight context object:


// Context - "Traffic Light", has internal state - one of the above.
// The behaviour changes accordingly to the current state
class TrafficLight
{
// Has properties that define it's behaviour
public int Pause { get; set; }
public string Color { get; set; }

// Has internal State
public ITrafficLightState NextState { get; set; }

// Sets the default state
public TrafficLight()
{
this.NextState = new RedLightState();
}


// Receives request ...
public void Request()
{
// ... then:
// Delegates to the internal State to handle.
NextState.Handle(this);

// The behaviour has changed, color, time of light, etc.
Console.WriteLine(Color);
System.Threading.Thread.Sleep(Pause * 1000);
}
}



And with this we are ready to give a try of our implementation, which looks like this now:





To demonstrate the traffic light we run an infinite loop and call the method Request() on instance of TrafficLight:


static void Main(string[] args)
{
// Demonstrate how TrafficLight works
TrafficLight trafficLight = new TrafficLight();
while (true)
trafficLight.Request();
}



Usage of State pattern



In our example the state of the Context object was changed from the state object itself. But it is not necessarily to be done this way. We can implement a Coffee Machine to run Short, Tall, Grand coffee. Then the state would be changed pressing a button on the Machine. Or we could use State pattern to switch between simple and advanced preview on a form. Then probably the Handle() function will just change the preview but not the user preferences.

Atanas Hristov

kick it on DotNetKicks.com
Shout it

Monday, January 4, 2010

Implementing and Using Repositories with NHibernate

Following the podcasts of the MVC Storefront Project at the time learning the ASP.NET MVC framework was for me really good introduction to the ideas of the Domain Driven Design (DDD).

Now, months later and still new to the DDD, but very enthusiastic, I’ll try to sketch some ideas I learned so far and in practice to implement a complete example. In particular I’ll be utilizing the Repository pattern and implement it with NHibernate as data access framework. I’m using NHibernate but I keep in mind to provide a layer of abstraction and to make it possible to switch to another data access provider (Entity Framework for example).

The Repository Pattern



Accordingly to Martin Fowler:

“A Repository mediates between the domain and data mapping layers, acting like an in-memory domain object collection. Client objects construct query specifications declaratively and submit them to Repository for satisfaction. Objects can be added to and removed from the Repository, as they can from a simple collection of objects, and the mapping code encapsulated by the Repository will carry out the appropriate operations behind the scenes. Conceptually, a Repository encapsulates the set of objects persisted in a data store and the operations performed over them, providing a more object-oriented view of the persistence layer. Repository also supports the objective of achieving a clean separation and one-way dependency between the domain and data mapping layers“.

The Repository encapsulates the actual storage and querying and keeps the client to focus on the model. We can use dependency injection and inversion of control to switch real and fake repositories for the needs of testing. We have also all the querying logic in centralized part of the application and it makes the support easier. Our application depends on simple in-memory collections, etc.


The Business Model



We have pretty simple bookstore model. We have only two kinds of objects: Books and Authors. A book can be written by one or many authors. One author can take part of writing one or more books. So, the relation between them is many-to-many.

The final database model could be similar to this:


Domain Entity Objects and Approval Services



In DDD Entity is an object fundamentally defined by thread of continuity and identity.

Value object is then an object that has properties (shapes) and does not have identity. Usually these are read-only object we use as data transfer object (DTO).

In an “ideal” world the entity objects does not have properties, but exposes operations (methods). To change the internal state of entity object we call its methods and send there value objects as parameters.

In this example our entity objects will have properties and we directly will access them to change the information contained in our entities.

When changing the properties of the entity objects we’ll need a possibility to validate the state of the entity object. We use the validation for example to show the end user an error message and prevent storing object to the database if it does not have valid state. The book object for example should have a title. We need a way the entity does validation of itself. Also, same entity object can be valid in one context, but in another context with same containing data to be invalid. We’ll inject a validator object that will implement the rules of the validation.

The validator object is kind of a Service object and is an operation. It does not belong to any object, but just checks if the properties of the entity object pass some rules. The dependency injection will be exposed via property which we name “Approval”.

The EntityBase class is from where all our entities will inherit:


/// <summary>
/// EntityBase represents objects primary defined by it's identity (Id).
/// The type of the identity, usually but not necessariily is of
/// type integer and is automatically assigned primary key.
///
/// All of the domain entities inherit this base class.
/// All of the domain entities have an identity and are able
/// to state if the data they contain is valid.
///
/// To check if the entity object contains valid data, they expose
/// property named Approval which is a concrete implementation of
/// ApprovalBase. The entity's Validate() method just wraps
/// the Approval.Validate(). The validation of entity returns list
/// of error messages and there is also a shortcut methnod IsValid()
/// which just gives back true if the validation was successful
/// or false if the validation has failed.
///
/// The entity objects implement IComparable interface and equality tests.
/// The have Equals() method to check if two variables point to same instance
/// of the same entity class and also they have equality operators that check
/// if the IDs are same.
/// </summary>
public abstract class EntityBase<TIdentity> where TIdentity : IComparable
{
// Gets or sets the identity.
public virtual TIdentity Id { get; set; }

protected EntityBase(TIdentity Id) { this.Id = Id; }

protected EntityBase() { }

// Approval object that does the validation.
public abstract ApprovalBase Approval { get; set; }

// Validation
public virtual IList<String> Validate()
{
if (Approval != null)
return Approval.Validate(this);
else
return new List<String>();
}

// Validation shortcut
public virtual bool IsValid()
{
return (Validate().Count == 0);
}


// Equality tests /////////////

// Determines whether the specified entity parameter
/// is equal to the current object (is the same reference)
public override bool Equals(object entity)
{
if (entity == null || !(entity is EntityBase<TIdentity>))
return false;

return (this == (EntityBase<TIdentity>)entity);
}

// Check if two entities have same ID
public static bool operator ==(EntityBase<TIdentity> entity1, EntityBase<TIdentity> entity2)
{
object obj1 = entity1 as object;
object obj2 = entity2 as object;

if ((obj1 == null) && (obj2 == null))
return true;

if ((obj1 == null) || (obj2 == null))
return false;

if (entity1.GetType() != entity2.GetType())
return false;

if (entity1.Id.CompareTo(entity2.Id) != 0)
return false;

return true;
}

// Check if two entities have different ID
public static bool operator !=(EntityBase<TIdentity> entity1, EntityBase<TIdentity> entity2)
{
return (!(entity1 == entity2));
}

// GetHashCode() if the Id.
public override int GetHashCode() { return this.Id.GetHashCode(); }
}




Then we inject an approval object to our entities and the approval objects inherit from ApprovalBase:


/// <summary>
/// The entity objects have property based
/// dependency injection with approval object.
///
/// If the entity has approval object,
/// the entity can be validated to prevent saving
/// entities with incorrect values, or to inform the
/// end user that the data he has entered is invalid.
///
/// The validation can be changed according to the context
/// the entity is in. In one situation the entity may be valid, but
/// in other situation the same entity with same properties
/// may not be valid.
///
/// The ApprovalBase is an abstract class from wich the concrete approval
/// classes will inherit. The ApprovalBase has method Validate wich returns
/// List of ApprovalErrorMessage error messages.
/// </summary>
public abstract class ApprovalBase
{
public abstract IList<String> Validate<TEntity>(TEntity entity);
}






Finder Objects



I found the ideas from Russell East’s blog "Implementing the Repository and Finder patterns" to be very promising and I think it is a very advanced way of implementing repositories.

For the original idea, please refer to:

http://russelleast.wordpress.com/2008/09/20/implementing-the-repository-and-finder-patterns/

I'm just following the same pattern here. The querying repositories depend on finder and persistence repositories.

One goals of Russell's idea is to keep independent from concrete Object Relational Mapper (ORM). Other goal is to have typed repositories - one per entity - and thereof make it possible to inject finder objects to the repositories. Also, he makes possible to inject the concrete persistance layer via inversion of control and provides fully testable implementation of repository.


All the entity finders extend a base IEntityFinder interface. The generic type is constrained by the EntityBase type.
The IEntityFinder interface is not to be used directly, but to be extended by typed Repository interfaces.



public interface IFinder<TEntity, TIdentity>
where TEntity : EntityBase<TIdentity>
where TIdentity : IComparable
{
// Has a DataSource property of IQueryable on which
// we use LINQ for quering.
IQueryable<TEntity> DataSource { get; set; }

/// Get count of objects/records.
int Count();

/// Find by id. We have entityConcrete = repositoryConcrete.Find.ById(123) like usage.
TEntity ById(TIdentity id);
}


All the finder object inherit from FinderBase class. The Finder objects implement search logic/functions using LINQ. The classes inherited from RepositoryBase (see below) have then object Find, which method names by convention look like "ById", "ByName", etc. The concrete finders have to implement at least ById method.


public abstract class FinderBase<TEntity, TIdentity>
: IFinder<TEntity, TIdentity>
where TEntity : EntityBase<TIdentity>
where TIdentity : IComparable
{
public IQueryable<TEntity> DataSource { get; set; }

/// Gets count of records.
public int Count()
{
return DataSource.Count();
}

/// Find one entity by ID.
public abstract TEntity ById(TIdentity id);
}



Base Repository Class



Let’s first define how the concrete persistence layer should look like.

The concrete ORM specific implementation is abstracted with interface IPersistor.

The repository takes care for querying; the persistence repository takes care for persistence and depends on ORM specific implementation.

The basic operations in the contract declared by this interface are: get entity by id; save entity to persist; delete entity from persist repository; get the query object on top of which to implement concrete LINQ queries.


public interface IPersistor<TEntity, TIdentity>
{
TEntity Get(TIdentity id);
void Save(TEntity entity);
void Delete(TEntity entity);
IQueryable<TEntity> Query();
}


Now we are about to finish the base repository class.

All the repositories extend a base IRepository interface. The generic type is restricted to be EntityBase type.
The basic operations in the contract are much the same like the defined in IPersistor, but we don't expose IQueryable to public, as we implement all the querying logic into the concrete repositories.


public interface IRepository<TEntity, TIdentity>
where TEntity : EntityBase<TIdentity>
where TIdentity : IComparable
{
TEntity Get(TIdentity id);
IList<String> Save(TEntity entity);
void Delete(TEntity entity);
// hidden // IQueryable<TEntity> Query();
}



The RepositoryBase is an abstract class from which all concrete repositories inherit from.
The repositories are injected with concrete entity types using the typed interface, so we have one repository per entity.
The repository class must be supplied an instance of IPersistor and an instance of IFinder.

public abstract class RepositoryBase<TEntity, TIdentity>
: IRepository<TEntity, TIdentity>
where TEntity : EntityBase<TIdentity>
where TIdentity : IComparable
{
private readonly IPersistor<TEntity, TIdentity> persistor;
public IPersistor<TEntity, TIdentity> Persistor { get { return persistor; } }

private readonly IFinder<TEntity, TIdentity> finder;
public IFinder<TEntity, TIdentity> Finder { get { return finder; } }

private RepositoryBase() { }

public RepositoryBase(
IPersistor<TEntity, TIdentity> persistor,
IFinder<TEntity, TIdentity> finder)
{
this.persistor = persistor;
this.finder = finder;
this.finder.DataSource = Query();
}

// Get entity by ID
public virtual TEntity Get(TIdentity id)
{
return persistor.Get(id);
}

/// <summary>
/// Validate and Save the entity. If the validation failed, will not save the entity,
/// but returns back list of error messages.
/// </summary>
public virtual IList<String> Save(TEntity entity)
{
if (entity == null)
throw new ArgumentNullException("entity");

IList<String> errors = entity.Validate();

if (errors.Count == 0)
persistor.Save(entity);

return errors;
}

// Delete entity from persistance repository
public virtual void Delete(TEntity entity)
{
if (entity == null)
throw new ArgumentNullException("entity");

persistor.Delete(entity);
}

/// Gets IQueryable which we use from the concrete
/// implementation of repository to implement our
/// query methods (FindBy).
protected IQueryable<TEntity> Query()
{
return persistor.Query();
}
}

The Book Store Model –Entities and Approvals




At this point I’ll define the book store model, its entities, and approval objects.

The Book object has along with title, publisher info, ISBN also a list of one or many authors.


public class Book : EntityBase<int>
{
public Book() : base()
{
this.Authors = new List<Author>();
}
public Book(int id) : this() { Id = id; }
public override ApprovalBase Approval { get; set; }

public virtual string Title { get; set; }
public virtual string Publisher { get; set; }
public virtual string ISBN { get; set; }

public virtual IList<Author> Authors { get; private set; }
}


An Author have a name and also eventually takes part on writing several books.


public class Author : EntityBase<int>
{
public Author() : base()
{
this.Books = new List<Book>();
}
public Author(int id) : this() { Id = id; }
public override ApprovalBase Approval { get; set; }

public virtual string Name { get; set; }
public virtual IList<Book> Books { get; private set; }
}


Please note that the properties of the entities are marked as “virtual” as it is required by NHibernate.

How let’s create some approval services. Again – we can switch the approval the entity has even at run time as we have property injection implemented in our entities and they don’t depend on concrete approval services. If we set the approval of the entity to null, the validation will be successful regardless the data the entity contains.


To check if Book object contains valid data we implement BookApproval. A Book should have title and at least one author.


public class BookApproval : ApprovalBase
{
public override IList<String> Validate<TEntity>(TEntity entity)
{
List<String> errors = new List<String>();
Book book = entity as Book;

if (book == null)
throw new ArgumentException("Entity not a book");

if (String.IsNullOrEmpty(book.Title))
errors.Add("Title can not be empty");

if ((book.Authors == null) || (book.Authors.Count == 0))
errors.Add("A book should have at least one author");

return errors;
}
}


To check if Author object contains valid data we implement AuthorApproval. An Author should have name.


public class AuthorApproval : ApprovalBase
{
public override IList<String> Validate<TEntity>(TEntity entity)
{
List<String> errors = new List<String>();
Author author = entity as Author;

if (author == null)
throw new ArgumentException("Entity is not an author");

if (String.IsNullOrEmpty(author.Name))
errors.Add("Name can not be empty");

return errors;
}
}



Okay, sometimes they are some “no name” authors. If you think so, you still can create your own implementation of AuthorApproval service :-)

The Book Store Model – Repositories and Finders



First we define interfaces which the client code will use when talking to the book store repositories.

The IBookFinder states that we should have one new method, not required by IFinder, and this is ByISBN().
The IBookRepository exposes Find property of type IBookRepository.


public interface IBookFinder : IFinder<Book, int>
{
Book ByISBN(string ISBN); // adds new find methiod
}
public interface IBookRepository : IRepository<Book, int>
{
IBookFinder Find { get; }
}


Similarly the same way for the Author:


public interface IAuthorFinder : IFinder<Author, int>
{
Author ByName(string name);
}
public interface IAuthorRepository : IRepository<Author, int>
{
IAuthorFinder Find { get; }
}


Then we create concrete BookFinder and BookRepository

public class BookFinder : FinderBase<Book, int>, IBookFinder
{
public override Book ById(int id)
{
return DataSource.Where(b => b.Id == id).FirstOrDefault();
}
public Book ByISBN(string ISBN)
{
return DataSource.Where(b => b.ISBN == ISBN).FirstOrDefault();
}
}

public class BookRepository : RepositoryBase<Book, int>, IBookRepository
{
public BookRepository(
IPersistor<Book, int> persistor,
IBookFinder entityFinder)
: base(persistor, entityFinder) { }

public IBookFinder Find
{
get { return (IBookFinder)Finder; }
}
}


and also concrete AuthorFinder and AuthorRepository


public class AuthorFinder : FinderBase<Author, int>, IAuthorFinder
{
public override Author ById(int id)
{
return DataSource.Where(a => a.Id == id).FirstOrDefault();
}
public Author ByName(string name)
{
return DataSource.Where(a => a.Name == name).FirstOrDefault();
}
}

public class AuthorRepository : RepositoryBase<Author, int>, IAuthorRepository
{
public AuthorRepository(
IPersistor<Author, int> persistor,
IAuthorFinder finder)
: base(persistor, finder) { }

public IAuthorFinder Find
{
get { return (IAuthorFinder)Finder; }
}
}





The Book Store Model – External Dependencies



Until now we have a model for our book store. This model is fully testable and we can test how it works and inject some stubs for finders, approvals, etc. if it is needed. Here we go further and finish our work as we implement the rest of the book store with some dependencies to external projects. We will use NHibernate as ORM and furthermore FluentNHibernate. We will use StructureMap for inversion of control. We will need few ADO.NET drivers for different databases, as we will be able to switch between them on demand. At the end we will create in memory SQLite database and test our book store..

Download and unpack these files and add references from the solution explorer:

Download: fluentnhibernate-binary-1.0.0.595.zip from http://fluentnhibernate.org/
Referenced assemblies: Antlr3.Runtime.dll, Castle.Core.dll, Castle.DynamicProxy2.dll, FluentNHibernate.dll, Iesi.Collections.dll, NHibernate.dll, NHibernate.ByteCode.Castle.dll

Download: NHibernate.Linq-1.0.0.GA-bin.zip from http://sourceforge.net/projects/nhibernate/files/
Referenced assemblies: NHibernate.Linq.dll

Download: SQLite-1.0.65.0-binaries.zip from http://sqlite.phxsoftware.com
Referenced assemblies: System.Data.SQLite.DLL, System.Data.SQLite.Linq.dll

Download: Npgsql2.0.7-bin-ms.net3.5sp1.zip from http://npgsql.projects.postgresql.org/
Referenced assemblies: Npgsql.dll, Mono.Security.dll

Download: StructureMap_2.5.3.zip from http://structuremap.sourceforge.net/Default.htm
Referenced assemblies: StructureMap.dll

Download: xunit-1.5.zip from http://www.codeplex.com/xunit
Referenced assemblies: xunit.dll, xunit.extensions.dll



Place the following “using” directives at the beginning of the code file:


using NHibernate;
using NHibernate.Cfg;
using NHibernate.Linq;
using NHibernate.Tool.hbm2ddl;
using FluentNHibernate.Mapping;
using FluentNHibernate.Cfg;
using FluentNHibernate.Cfg.Db;
using StructureMap;







The Book Store Model – FluentNHibernate mappings



From the “Getting started” wiki page of the of the Fluent NHibernate project:
“Fluent NHibernate offers an alternative to NHibernate's standard XML mapping files. Rather than writing XML documents (.hbm.xml files), Fluent NHibernate lets you write mappings in strongly typed C# code. This allows for easy refactoring, improved readability and more concise code“.

We create dedicated classes to map the book store entity objects to tables into the database. For the entity’s identity NHibernate will automatically create automatically generated (auto incremented) values. The mapper class derive from FluentNHibernate.Mapping .ClassMap


public sealed class BooksMap : ClassMap<Book>
{
public BooksMap()
{
Id(x => x.Id);
Map(x => x.Title).Length(256).Default("").Not.Nullable();
Map(x => x.Publisher).Length(256).Default("").Nullable();
Map(x => x.ISBN).Length(16).Default("").Not.Nullable();
HasManyToMany(x => x.Authors).LazyLoad();
}
}
public sealed class AuthorsMap : ClassMap<Author>
{
public AuthorsMap()
{
Id(x => x.Id);
Map(x => x.Name).Length(128).Default("").Not.Nullable();
HasManyToMany(x => x.Books).LazyLoad();
}
}



The Book Store Model –NHibernate Persistors



As we defined concrete repositories and finders for the book and author entities, still we don’t have concrete persistors. First we define base persistor which depends on NHibernate (uses NHibernate.ISession, etc). Then we define the persistors for our entities.



// Concrete NHibernate based persistance repository.
public abstract class PersistorBase<TEntity, TIdentity>
: IPersistor<TEntity, TIdentity>
{
protected ISession Session { get; set; }

public PersistorBase(ISession session)
{
Session = session;
}

public TEntity Get(TIdentity id)
{
return (TEntity)Session.Get(typeof(TEntity), id);
}

public void Save(TEntity entity)
{
Session.SaveOrUpdate(entity);
}

public void Delete(TEntity entity)
{
Session.Delete(entity);
}

public IQueryable<TEntity> Query()
{
var qry = from t in Session.Linq<TEntity>()
select t;

return qry.AsQueryable();
}
}

// Persistance repository for books.
public class BookPersistor : PersistorBase<Book, int>
{
public BookPersistor(ISession session) : base(session) { }
}

// Persistance repository for authors.
public class AuthorPersistor : PersistorBase<Author, int>
{
public AuthorPersistor(ISession session) : base(session) { }
}





The Book Store Model –NHibernate initialization



How comes stuff completely related to NHibernate and not directly to the book store model.

BaseDatabase is wrapper class for NHibernate initialization - a class from which concrete per database driver/server implementations will be created.

From this one we create implementation for Postgres, for MySQL, for SQLite, etc.
Into the concrete implementations we switch drivers, connection string, etc.

In Init() we open connection to the database.
The BuildSchema() method creates the database tables, relations, etc.


public abstract class BaseDatabase : IDisposable
{
protected static Configuration configuration;
protected static ISessionFactory sessionFactory;

public ISession Session { get; protected set; }

/// Does initialization, run from the constructors of the inherited classes.
protected void Init()
{
sessionFactory = CreateSessionFactory();
Session = sessionFactory.OpenSession();
BuildSchema(Session);
}

protected abstract ISessionFactory CreateSessionFactory();

private static void BuildSchema(ISession session)
{
SchemaExport schemaExport = new SchemaExport(configuration);
schemaExport.Execute(true, true, false, session.Connection, null);
}

public void Dispose()
{
Session.Dispose();
}

}


And now I implement some concrete initializations per database driver/server:



/// Database configured as in file SQLite database.
public class SQLiteInFileDatabase : BaseDatabase
{
public string FileName { get; private set; }

/// Create SQLite database with specified file name.
public SQLiteInFileDatabase(string fileName)
{
// file name to store the database, "database.db" for example.
FileName = fileName;

// does not run the base constructor, but calls Init() by itself.
Init();
}

protected override ISessionFactory CreateSessionFactory()
{
return Fluently.Configure()
.Database(SQLiteConfiguration.Standard.UsingFile(FileName).ShowSql())
.Mappings(m => m.FluentMappings.AddFromAssemblyOf<BooksMap>())
.ExposeConfiguration(Cfg => configuration = Cfg)
.BuildSessionFactory();
}
}

/// Database configured as in memory SQLite database.
public class SQLiteInMemoryDatabase : BaseDatabase
{
/// Create in memory SQLite database.
public SQLiteInMemoryDatabase()
{
Init();
}

protected override ISessionFactory CreateSessionFactory()
{
return Fluently.Configure()
.Database(SQLiteConfiguration.Standard.InMemory().ShowSql())
.Mappings(m => m.FluentMappings.AddFromAssemblyOf<BooksMap>())
.ExposeConfiguration(Cfg => configuration = Cfg)
.BuildSessionFactory();
}
}


/// Database configured as in memory SQLite database.
public class PostgresDatabase : BaseDatabase
{
public string ConnectionString { get; private set; }

/// Create in memory SQLite database.
public PostgresDatabase(string connectionString)
{
ConnectionString = connectionString;
Init();
}

protected override ISessionFactory CreateSessionFactory()
{
return Fluently.Configure()
.Database(PostgreSQLConfiguration.PostgreSQL81
.ConnectionString(ConnectionString).ShowSql())
.Mappings(m => m.FluentMappings.AddFromAssemblyOf<BooksMap>())
.ExposeConfiguration(Cfg => configuration = Cfg)
.BuildSessionFactory();
}
}






The Book Store Model – the BookStore database class



It is time for the book store class. The BookStore class contains book and author repository and does the necessary initialization of those. Also contains concrete instance of BaseDatabase. We inject concrete instance of BaseDatabase from the parameterized constructor. We also have parameter less constructor which leans upon StructureMap to init this singleton class with concrete instance and implementation of BaseDatabase.



/// Is a singleton, use GetInstance()
public class BookStore
{
private static BookStore bookStore;

public static BookStore GetInstance()
{
if (bookStore == null)
bookStore = new BookStore();
return bookStore;
}

private BaseDatabase db;
public IBookRepository BookRepository { get; private set; }
public IAuthorRepository AuthorRepository { get; private set; }


/// Inject concrete instance of BaseDatabase.
public BookStore()
: this(ObjectFactory.GetInstance<BaseDatabase>())
{ }

public BookStore(BaseDatabase db)
{
this.db = db;
Init();
}


private void Init()
{
IBookFinder bookFinder = new BookFinder();
BookPersistor bookPersistor = new BookPersistor(db.Session);
BookRepository = new BookRepository(bookPersistor, bookFinder);


IAuthorFinder authorFinder = new AuthorFinder();
AuthorPersistor authorPersistor = new AuthorPersistor(db.Session);
AuthorRepository = new AuthorRepository(authorPersistor, authorFinder);
}

// can be used to implement the Unit of Work Pattern.
public void Flush()
{
db.Session.Flush();
}
}






The Book Store Model – Usage


For the usage and to run the final example I’ll put the rest into the Program.cs file.

First I create two concrete implementation of BaseDatabase: SQLite where we have specified file name for our SQLite database and Postgres where we have specified the concrete connection string.

Then we have method ConfigureDependencies() to initialize StructureMap. We say which concrete class to be created whenever we create instance of BaseDatabase using the default parameter less constructor. Please note that we have such situation in class BookStore in GetInstance() where it creates an instance of itself. BookStore depends only on BaseDatabase class, but not on the concrete implementations of BaseDatabase. Then StructureMap will decide for the concrete implementation of BaseDatabase.




public class Program
{
public class SQLiteInFileConcreteDatabase : SQLiteInFileDatabase
{
public SQLiteInFileConcreteDatabase() : base("test.db") { }
}

public class PostgresConcreteDatabase : PostgresDatabase
{
public PostgresConcreteDatabase()
: base("Server=127.0.0.1;Port=5432;Database=bookstore;User Id=postgres;Password=;")
{ }
}

/// <summary>
/// Configure StructureMap dependencies.
/// </summary>
private static void ConfigureDependencies()
{
ObjectFactory.Initialize(x =>
{
x.ForRequestedType<BaseDatabase>()
.TheDefaultIsConcreteType<SQLiteInMemoryDatabase>();
// .TheDefaultIsConcreteType<SQLiteInFileDatabaseConcrete>();
// .TheDefaultIsConcreteType<PostgresConcreteDatabase>();
// whatever concrete database and settings
});
}



static void Main(string[] args)
{
ConfigureDependencies();

BookStore bookStore = BookStore.GetInstance();

Author JohnDoe = new Author() { Name = "John Doe" };
bookStore.AuthorRepository.Save(JohnDoe);

Author JaneDoe = new Author() { Name = "Jane Doe" };
bookStore.AuthorRepository.Save(JaneDoe);

Book book;

// test approval:
book = new Book() { };
book.Approval = new BookApproval();
Console.WriteLine("Approval of book: {0}", String.Join(System.Environment.NewLine, book.Validate().ToArray()));


// test saving to database
book = new Book() { Title = "Meet John Doe", ISBN = "1234567890123" };
book.Authors.Add(JohnDoe);
book.Authors.Add(JaneDoe);
bookStore.BookRepository.Save(book);
bookStore.Flush(); // moan on error

Book selected = bookStore.BookRepository.Find.ByISBN("1234567890123");
Console.WriteLine(String.Format("Author one: {0}", selected.Authors[0].Name));
Console.WriteLine(String.Format("Author two: {0}", selected.Authors[1].Name));
Console.ReadLine();
}
}



When I ran the program, I’ve got the following output:



I also gave a try of the BookApproval. The validation has failed with two error messages. Saving that book definition – with bookStore.BookRepository.Save(book); - wouldn’t be possible as the validation did not pass.



At the end I place some links related to the theme.

An excellent blog on implementing repository and finder pattern:
http://russelleast.wordpress.com/2008/09/20/implementing-the-repository-and-finder-patterns/

Part 2 from the Blog attending the MVC Storefront Project where the Repository Pattern is used:
http://blog.wekeroad.com/mvc-storefront/asp-net-mvc-mvc-storefront-part-2/

Fluent mapping for NHibernate
http://fluentnhibernate.org/

To download NHibernate.Linq
http://sourceforge.net/projects/nhibernate/files/

ADO.NET SQLite Data Provider:
http://sqlite.phxsoftware.com

ADO.NET Postgresql Data Provider:
http://npgsql.projects.postgresql.org/

StructureMap Inversion of Control Framework:
http://structuremap.sourceforge.net/Default.htm

Atanas Hristov

kick it on DotNetKicks.com
Shout it

Tuesday, December 1, 2009

Design Patterns – Memento Pattern

The Memento Pattern is useful to remember the state of object without keeping copy of the whole object. Copying of the entire object is sometimes inefficient as the copy eventually contains much more information that we need to restore back.



Memento



Memento is the object that can remember the internal state of another object.


// Memento. Uses deep copy and serialization
// to save/restore the state of type TState.
public class Memento<TState>
{
MemoryStream stream = new MemoryStream();
BinaryFormatter formatter = new BinaryFormatter();

public Memento<TState> Save(TState state)
{
formatter.Serialize(stream, state);
return this;
}

public TState Restore()
{
stream.Seek(0, SeekOrigin.Begin);
TState state = (TState)formatter.Deserialize(stream);
stream.Close();
return state;
}
}



The Memento in this example uses generics to ensure type consistence and prevent using type conversion.

Originator



Originator is the object which state to remember and restore back if needed. The Originator has two methods for that:
- GetMemento() that returns the state of the object
- and SetMemento() receives back state to restore from


// The Originator has one property that returns
// the complete state of the object.
public interface IOriginator<TState>
{
TState State { get; }
}

// Holds the state of the Originator
[Serializable]
public class ProductState
{
public string Name { get; set; }
public float Price { get; set; }
}

// Originator
// The complete state is moved to one property
// to generalize the memento pattern.
[Serializable]
public class Product : IOriginator<ProductState>
{
public Product()
{
this.State = new ProductState();
}

public Product(string name, float price)
: this()
{
this.State.Name = name;
this.State.Price = price;
}

public ProductState State { get; private set; }

public Memento<ProductState> GetMemento()
{
return new Memento<ProductState>().Save(State);
}

public void SetMemento(Memento<ProductState> memento)
{
State = memento.Restore();
}

public override string ToString()
{
return String.Format(System.Globalization.CultureInfo.InvariantCulture,
"{0} {1:f2}", State.Name, State.Price);
}
}




Caretaker



Caretaker is the object that controls when to create Memento but the Originator will use the stored into the Caretaker state to restore from.


// Usage example and Caretaker as the same time.
static void Main(string[] args)
{
// Caretaker is in this example the class that holds the Main() void
// or the Main() void itself of you want.
Memento<ProductState> memento = new Memento<ProductState>();

Product product = new Product("Name one", 100f);
Console.WriteLine("Initial state: " + product.ToString());

memento = product.GetMemento();
Console.WriteLine("The state was saved to memento");

// Change the state of the Originator
product.State.Name = "Name two";
product.State.Price = 200f;
Console.WriteLine("State changed: " + product.ToString());

// Change the state of the Originator
product.State.Name = "Name three";
product.State.Price = 300f;
Console.WriteLine("State changed: " + product.ToString());

product.SetMemento(memento);
Console.WriteLine("The state restored from memento");

Console.WriteLine("Reverted state: " + product.ToString());

Console.ReadLine();
}




which gives after running the following output:




The Memento is save-state undo command, where the captured is a backup. In this example the Memento object used in-memory storage to keep backup of state, but the Memento object could also even persist state into a database.

Atanas Hristov

kick it on DotNetKicks.com
Shout it

Saturday, October 31, 2009

AJAX publish/subscribe

Calling long running web server process and locking the user for a while in web applications with the typical for the HTTP request/replay way can be critical for the user expirience. Even more, possibly we don't get back the data due to problems with the network connection or browser timeouts.

Even if on top of unreliable protocol like HTTP we can provide some abstraction level to ensure we'll get the result from the web server. We could simulate the publish/subscribe pattern in ajax. Furthermore our communication with the web server is asynchronous and allows our application to respond better to the user interactions.

On the web server we could implement multithreading and open working threads which get the calculations done.

With javascript we send request to the web server and then in some interval of time we again and again ask if the server has prepared the result. When the web server has collected the information we need, we take the data from the web server, display on the page and stop the repetative calls to the web server.

I will implement publish/subscribe with ASP.NET MVC and jQuery.

The CityWeather model



First i'll create model class CityWeather. The only public properties of CityWeather object are "City" and "Temperature".

After CityWeather class created, the constructor calls Measure() in thread. The Measure() function simulates long running process used to collect the weather information for that city.

We store all the requests for measurements in static collection _measurements. The keys of this collection are the city names.

The only public function of the model class is the static function GetCityWeather() which when called will check if in _measurements exists object CityWeather for this city. If not will create one. The function returns back the corresponding CityWeather object from the _measurements collection.



namespace PublishSubscribe.Models
{
// Measurements per city.
// Call class method CityWeather.GetCityWeather(city)
// to get CityWeather object with measurements
// for that city.
// Repead calling CityWeather.GetCityWeather(city)
// until city.Temperature is not null.
public class CityWeather
{
// Holds all requested measurements.
// Used from class method GetCityWeather()
// The keys are city names.
// The values are CityWeather objects.
private static Dictionary<string, CityWeather> _measurements =
new Dictionary<string, CityWeather>();

// public properties of CityWeather object:
public string City { get; private set; }
public int? Temperature { get; private set; }


// The constructor itself starts measurement
// in an asynchronous thread.
private CityWeather(string city)
{
this.City = city;

// after the object is constructed will start
// doing measurement in a thread, which respectively
// takes some time
ThreadStart ts = new ThreadStart(Measure);
Thread th = new Thread(ts);
th.Priority = ThreadPriority.Lowest;
th.Start();
}

// Worker method started in separate thread from
// the constructor
private void Measure()
{
// measurement takes some time - up to a minute
Thread.Sleep(new Random().Next(1,6) * 10000);

// lock the object alowing concurent access
// to the object properties
lock (this)
// degrees Celsius between 10 and 20
Temperature = new Random().Next(10, 20);
}


// The only public method that capsulates all the logic
// of keeping single instances - one per city -
// just as static memory for the purpose of the
// demonstration.
//
// Keep calling CityWeather.GetCityWeather(city) until
// you get back an CityWeather object with
// property Temperature which is not null.
public static CityWeather GetCityWeather(string city)
{
lock (_measurements)
{
if (! _measurements.ContainsKey(city))
{
CityWeather cw = new CityWeather(city);
_measurements.Add(city, cw);
}

return _measurements[city]; // check
}
}
}
}



The usage of this class is pretty simple. We call the static function CityWeather.GetCityWeather() with the name of a city to get weather measurements for that city. We repeat the call again and again until we get back CityWeather object where Temperature property is set - is not null, but contains value.



The Weather controller



Then I'll create the controller class:



namespace PublishSubscribe.Controllers
{
public class WeatherController : Controller
{
public JsonResult Measure(string city)
{
return Json(Models.CityWeather.GetCityWeather(city));
}

public ActionResult Index()
{
return View();
}
}
}



The controller has two methods. Measure gets weather measurements for one given city. We send back JSON result.

The Index method we will use to create page where we will demonstrate how the AJAX publish/subscribe calls will work.

We are ready to try how the Measure JSON handler will respond and to see the how the CityWeather model will work. We run the application and navigate to /weather/measure where we request measurements for a city and repetative hit repoad on the browser until we receive back the Temperature calculated.

Here is how example session with repetative calls looks like:




URL: http://localhost:3284/weather/measure/?city=berlin
Response: {"City":"berlin","Temperature":null}
...
URL: http://localhost:3284/weather/measure/?city=berlin
Response: {"City":"berlin","Temperature":null}
...
URL: http://localhost:3284/weather/measure/?city=berlin
Response: {"City":"berlin","Temperature":12}




AJAX publish/subscribe with jQuery



Now I'm going to implement the web page to demonstrate the idea behind the AJAX publish/subscribe.

The html body tag is very simple.



<body>

<label for="city">City:</label>
<input type="text" id="txtCity" />
<input type="button" value="measure" id="btnMeasure" />

<table id="cites">
<thead>
<tr><td style="width:200px">City</td><td>Temperature</td></tr>
</thead>
<tbody>
</tbody>
</table>

</body>



We write city name into the input box and click the "measure" button. We repeat that several times with other city names. We expect whenever the server has measured the weather for a city we asked for, the result will be added to the table as new row. The order of the cities we ask for measurements is not necessarily the order we'll get back calculated measurements. The time the server will spend to take weather measurements may vary from city to city and is not presumable.

This way we will have asynchronious communication with the server and the user will appreciate the better respond from the application.


Last, I'll put some javascript after the closing body task and will automate the html page with jQuery.

As we don't have multithreading in javascript we simulate it with setInterval and clearInterval. We start repetative calls as we run sendMeasureRequest(city) every second and ask the web server if the measurements for that city are calculated. Once the server gives back calculated results we stop the repetative calls.

The setInterval() function gives us interval ID which we later use at calling clearInterval() to stop repetative tasks. Then we also need to map somewhere interval ID to city name, thereof we create array measurements which keys are city names. The values of the measurements dictionary are data structures wich hold interval ID, city name and the temperature as measured from the web server.

Once the web server respond calculated measurement we stop the corresponding repetative calls to the web server and call the function cityMeasured(). We add new row into the table with the measurements.



<script type="text/javascript">

/* Hash array of all collected measurememts */
var measurements = new Array();

/* Does weather measurement for a city */
function measureCity(city) {
if (measurements[city] == undefined) {
// send request to the server every one second
var intervalID = setInterval(sendMeasureRequest, 1000, city);
measurements[city] = {
IntervalID: intervalID,
City: city,
Temperature: null
};
sendMeasureRequest(city);
}
cityMeasured(city);
}

/* Send GET request to the server to collect weather measurements for a city */
function sendMeasureRequest(city) {
$.ajax({
'url': '<%= Url.Action("Measure") %>',
'type': 'GET',
'dataType': 'json',
'data': { 'city': city },
'success': function(data) {
if (data.Temperature != null) {
clearInterval(measurements[data.City].IntervalID);
measurements[data.City].Temperature = data.Temperature;
cityMeasured(data.City);
}
}
});
}

/* Does weather measurement for a city */
function cityMeasured(city) {
if (measurements[city].Temperature != null) {
if ($('#tr_' + city).length == 0) {
$("#cites > tbody").append('<tr id="tr_' + city + '"><td>'
+ measurements[city].City
+ '</td><td>'
+ measurements[city].Temperature + ' grad'
+ '</td></tr>');
}
}
$('#tr_' + city).fadeOut();
$('#tr_' + city).fadeIn();
}

/* SetUp click handler */
$(document).ready(function() {
$("#btnMeasure").click(function() {
var city = $("#txtCity").val();
measureCity(city);
});
});
</script>



After I ran the application and navigated to /weather/ I asked for weather measurements for the following cities in the exact order: Paris, Boston, Rom, Hamburg

Then I waited few seconds and the weather measurements were displayed to the page one after other:




Well, we may consider as next to be done, once the weather in city from the table has charnged, we refresh the information on the table.

Atanas Hristov

kick it on DotNetKicks.com
Shout it

Tuesday, October 13, 2009

Design Patterns – Abstract Factory Pattern

Factories are objects that encapsulate the logic for creating other objects.

Factory object could create one or another object based on some configuration parameters. Or the factory could decide what kind of concrete object to create based on a parameter to some object creational method. For example if the method received post-code the factory creates City object and when the parameter is an email address the factory creates Customer object. In that way one might create factory to select one or another kind of object from database based on the user input.

Abstract Factory



The Abstract Factory is that encapsulates the way of creating concrete objects that have lot of common.

Often the created from abstract factory objects derive from same base class or share some interface. Abstract factory object for example could be used to create fake objects for the purpose of testing the software, and create regular objects otherwise in production mode. The fake object and the regular object derive from same base class or share same interface. The client code deals only with instances of the base type and has no knowledge of the concrete implementation.

I will give an example of abstract factory created with C#.

Reflection based abstract factory



The central feature of our abstract factory is to create concrete objects based on key/value pairs.

We register the types the factory is able to create into a dictionary. For registration of the types the factory may create we expose method Register().

Our base abstract factory class uses reflection to call the object constructors of the concrete type. That is done in method CreateInstance(). We invoke CreateInstance() with:



  • key - that will be used to create one concrete object or another as it is registered already via Register().


  • typeParams - if the concrete object has parameterized constructor which we want to use, then we specify the parameter types in an array.


  • valParams - if the concrete object has parameterized constructor which we want to use, then we specify the parameter values in an array.





Following is a implementation of reflection based abstract factory:




// T1 is the appropriate key type.
// T2 is the base type from which derive all the types the factory can create.
public abstract class AbstractFactory<T1, T2>
{
// Creates the factory.
// T1 is the appropriate type.
// T2 is the base type from which derive all the types the factory can create.
public static AbstractFactory<T1, T2> CreateFactory()
{
throw new Exception("Override FactoryReflected.CreateFactory()!");
}

// Register for types the factory can create.
protected Dictionary<T1, Type> _registered = new Dictionary<T1, Type>();

// Registers the specified factory types.
protected void Register(T1 key, Type type)
{
_registered.Add(key, type);
}


// Creates new instance of type by enumeration key.
public T2 CreateInstance(T1 key, Type[] typeParams, object[] valParams)
{
Type type = _registered[key];

System.Reflection.ConstructorInfo cInfo =
type.GetConstructor(typeParams);

return (T2)cInfo.Invoke(valParams);
}

}


We also have used generics to make the implementation of reflection based abstract factory more generalized.




Personal name



Let's face the problem and how we are going to find a solution. The different societies have different conventions for personal full name. In Russia the common order is "family-name given-name". In some situations the family-name is capitalized. In west Europe the usual convention is "given-name family-name", etc.

Our problem is - we are going to use the appropriate form of address when we communicate with people from different regions. For simplicity assume we have the family and the given name. We need a way to compose appropriate full name.

First we have the base class Name. The Name class has first and last name properties. We also have an abstract method GetFullName() which should give different result for different society. Furthermore, the concrete implementation will be done in derived classes:



// Base abstract class from which concrete implementations derive
public abstract class Name
{ // see http://en.wikipedia.org/wiki/Full_name#Naming_convention

protected string firstName;
protected string lastName;
protected Name() { }
public Name(string first, string last)
{
this.firstName = first;
this.lastName = last;
}

// Full name can be composed differently
// as the different societies have they different
// naming conventions
public abstract string GetFullName();
}

// composing Western full name
public class WesternName : Name
{
public WesternName(string first, string last) : base(first, last) { }
public override string GetFullName() { return firstName + " " + lastName; }
}

// composing Eastern full name
public class EasternName : Name
{
public EasternName(string first, string last) : base(first, last) { }
public override string GetFullName() { return lastName + " " + firstName; }
}

// another Eastern full name convention
public class EasternOfficialName : Name
{
public EasternOfficialName(string first, string last) : base(first, last) { }
public override string GetFullName() { return lastName.ToUpper() + " " + firstName; }
}





Concrete factory



Having the abstract factory from above we create concrete factory used for creation of objects of classes derived from the Name class. The NameFactory contains the initialization of itself in method CreateFactory(). If we create new concrete class derived from class Name to fit another convention for personal full name then we also have to register that new class in CreateFactory() method.



public class NameFactory : AbstractFactory<string, Name>
{
private NameFactory() { }

public static new NameFactory CreateFactory()
{
NameFactory factory = new NameFactory();

// Register which concrete type to create for which key
factory.Register("WesternOrder", typeof(WesternName));
factory.Register("EasternOrder", typeof(EasternName));
factory.Register("EasternOfficialOrder", typeof(EasternOfficialName));

return factory;
}
}




We will create instances of NameFactory only via the static method CreateFactory() and thereof we have specified the default constructor to be private.






Using the concrete factory



We create nameFactory object and then call one after another GetFullName() of all possible derived from class Name objects. These derived from Name objects we create as we call method CreateInstance() of nameFactory.



class Program
{
static void Main(string[] args)
{
NameFactory nameFactory = NameFactory.CreateFactory();

foreach (string convention in new string[] {
"WesternOrder", "EasternOrder", "EasternOfficialOrder", })
{
Name name = nameFactory.CreateInstance(convention,
new Type[] { typeof(string), typeof(string) },
new object[] { "Atanas", "Hristov" });

Console.WriteLine(name.GetFullName());
}


Console.Read();
}
}



And finally the output to the console:






Atanas Hristov

kick it on DotNetKicks.com
Shout it

Friday, September 25, 2009

Design Patterns – Singleton Pattern

The Singleton pattern gives us a way to restrict the instantiation of objects of given class to certain number, in the common usage to one only.

The Singleton class instantiates itself and works as a global repository for an instance of itself. For example we share a database connection or log writer across all threads in one process.

Implementation of Singleton pattern



Here i'm going to implement Singleton class in C#. The class should hide its constructor. It has also GetInstance() method that gives back the only concrete instance. We embed the concrete instance of the class into the static variable "obj".

For the purpose of the demonstration we have one public method Add() used to add some number to the class and Total() which gives back the total of the added numbers.



public class Singleton
{
private static Singleton obj = new Singleton(); // holds a reference to the only concrete instance

private static int total = 0; // we add numbers up to this via Add()

private Singleton() { } // hiden constructor

public static Singleton GetInstance() { return obj; } // returns the only concrete instance

public void Add(int number)
{ // add up to the total
lock (obj) // synchronize in concurrency
{
Thread.Sleep(new Random().Next(1000)); // randomly wait up to a second
total += number;
Console.WriteLine(String.Format("Add {0} to total", number));
}
}

public int Total()
{ // gets the total
lock (obj)
return total;
}
}




In Add() method we have a timeout up to a second to randomize the time to run the method.

We also locked the access to the class variables for concurrency. We are going to test the Singletion class in multithreaded environment.


Usage of Singleton pattern




First we create three static helper methods which will make calls to Add() with different number from one to three.



class Program
{
// add
static void HelperOne() { Singleton.GetInstance().Add(1); }
static void HelperTwo() { Singleton.GetInstance().Add(2); }
static void HelperThree() { Singleton.GetInstance().Add(3); }
...



Then in Main() we run three threads and run concurrently the three static helper methods.

We wait for the threads to finish and show the total of all additions to the singleton class.




static void Main(string[] args)
{
Thread[] threads = new Thread[]
{
new Thread(new ThreadStart(HelperOne)),
new Thread(new ThreadStart(HelperTwo)),
new Thread(new ThreadStart(HelperThree))
};

foreach (Thread thread in threads) { thread.Start(); }
foreach (Thread thread in threads) { thread.Join(); }

Console.WriteLine(String.Format("The total is {0}",
Singleton.GetInstance().Total()));

Console.Read();

}



Run the example



Running that I've got the following output:




Happy codding!

Atanas Hristov


Shout it

Friday, September 11, 2009

Design Patterns – Chain of Responsibility Pattern

Imagine you have complicated decision logic and you’ve got a big if-then-else like structure in your code which you want to simplify.
The Chain of Responsibility Pattern is a good way for code refactoring in such situation. It will make the code more flexible and easy to support and modify in the future.

You prepare a set of interdependent chain handler classes linked in a chain. Every chain handler class implements part of the decision logic and has a link to next chain handler object. A request data object is passed thru the chain. Eventually one of the handlers on the chain matches some decision criteria, does data processing and ends up the run flow. This would be the handler objects in the chain that takes the responsibility and does data processing having received the request data object.

In this example we will try to programmatically come up with a conclusion based on passed in to the chain two boolean parameters. For every possible combination of those parameters we are going give a conclusion back, so we have four different possible results. Otherwise we could do things using conditional structures like:



If Param1 is true
If Param2 is true
Conclusion1
Else
Conclusion2
Else
If Param2 is true
Conclusion3
Else
Conclusion4


Based on that conditional structure we will create chain of responsibility with four different chain handler classes covering all decision making combinations.

We will use C# as a programming language for the examples.

Chain Handler Interface and Base Class



We start with the definition of the chain handler interface. The chain handler object stores internally a request data object. We have a way to set if there is a handler next on the chain. The handler has Run() void where the decision making and eventually data processing will be done.



// All handler objects implement common interface.
// T: request object- holds data to process
// and the result of the processing
public interface IChainHandler<TRequest>
{
IChainHandler<TRequest> SetNextLink(IChainHandler<TRequest> next); // set link to next handler
void Run(); // does processing
}



As we will have four chain handler classes and they all have a lot in common, we create parent abstract base class for chain handler.



// base class for all concrete chain handler objects
public abstract class ChainHandlerBase : IChainHandler<RequestData>
{
// the request data object
protected RequestData _requestData;

// a reference to next chain handler object
private IChainHandler<RequestData> _nextHandler;

// hide parameterless constructor
private ChainHandlerBase() { }

// expose constructor with parameters
public ChainHandlerBase(RequestData requestData)
{
_requestData = requestData;
}
// set the reference to the next chain handler object
public IChainHandler<RequestData> SetNextLink(IChainHandler<RequestData> nextHandler)
{
_nextHandler = nextHandler;
return _nextHandler;
}

// let the concrete implementation make processing decision
public abstract void Run();

// run next handler in the chain if defined or end up the processing
protected void RunNext()
{
if (_nextHandler != null)
_nextHandler.Run();
}

}



Request Data Object



A step back – we need to define the request data object which we’ll pass thru the chain. This object holds two input boolean parameters and a holder where we write the conclusion message back.



// Data to pass thru the chain.
// Based on this data the chain
public class RequestData
{
// pass in parameters
public bool HaveLotOfMoney { get; set; }
public bool HaveBrilliantIdea { get; set; }

// a message to send back
public string MessageBack { get; set; }
}




Concrete Chain Handler Implementations



Now we are ready to define concrete chain handler classes and cover all possible combinations of the input parameters.



// concrete chain handler object
public class ChainHandlerOne : ChainHandlerBase
{
public ChainHandlerOne(RequestData requestData) : base(requestData) { }
public override void Run()
{
if ((_requestData.HaveLotOfMoney) && (_requestData.HaveBrilliantIdea))
{
_requestData.MessageBack = "I am with you.";
return;
}
RunNext();
}
}

// concrete chain handler object
public class ChainHandlerTwo : ChainHandlerBase
{
public ChainHandlerTwo(RequestData requestData) : base(requestData) { }
public override void Run()
{
if ((_requestData.HaveLotOfMoney) && (!_requestData.HaveBrilliantIdea))
{
_requestData.MessageBack = "Well done. Go on pension.";
return;
}
RunNext();
}
}

// concrete chain handler object
public class ChainHandlerThree : ChainHandlerBase
{
public ChainHandlerThree(RequestData requestData) : base(requestData) { }
public override void Run()
{
if ((!_requestData.HaveLotOfMoney) && (_requestData.HaveBrilliantIdea))
{
_requestData.MessageBack = "What a nice idea.";
return;
}
RunNext();
}
}

// concrete chain handler object
public class ChainHandlerFour : ChainHandlerBase
{
public ChainHandlerFour(RequestData requestData) : base(requestData) { }
public override void Run()
{
if ((!_requestData.HaveLotOfMoney) && (!_requestData.HaveBrilliantIdea))
{
_requestData.MessageBack = "Don't give up.";
return;
}
RunNext();
}
}




Set Up the Chain



We are ready at this point to put in order the chain. We create chain handler objects and link them in a appropriate order. We send to the first handler in the chain a request data object and hit the Run() method to get the result calculated.



// wraps the chain initialization and processing code
static RequestData WhatAboutMe(RequestData requestData)
{
// construct the first chain handler.
ChainHandlerBase firstHandler = new ChainHandlerOne(requestData);

// arrange chain of responsibility as list of chain handker objects
firstHandler
.SetNextLink(new ChainHandlerTwo(requestData))
.SetNextLink(new ChainHandlerThree(requestData))
.SetNextLink(new ChainHandlerFour(requestData));

// start processing of the request data
firstHandler.Run();

// return back the request data with the message created
return requestData;
}



Run the Chain



The win of utilizing chain responsibility pattern is the extensibility of our code in future. If we need additional logic we have to implement new chain handler class. We also may construct the chains in one or another way, we can order the chain handler object based on concrete needs. We absolutely take care of single responsibility principle and we divide a long and complicated to maintain code into well testable small classes.

Finally let’s run our chain of responsibility implementation. We’ll send every possible combination of input to the chain and see what’ll happen.




static void Main(string[] args)
{
Console.WriteLine(WhatAboutMe(new RequestData {
HaveLotOfMoney = true, HaveBrilliantIdea = true }).MessageBack);

Console.WriteLine(WhatAboutMe(new RequestData {
HaveLotOfMoney = true, HaveBrilliantIdea = false }).MessageBack);

Console.WriteLine(WhatAboutMe(new RequestData {
HaveLotOfMoney = false, HaveBrilliantIdea = true }).MessageBack);

Console.WriteLine(WhatAboutMe(new RequestData {
HaveLotOfMoney = false, HaveBrilliantIdea = false }).MessageBack);

Console.Write("Hit Enter to finish.");
Console.ReadLine();
}



Running that we get on the console like:



Atanas Hristov

kick it on DotNetKicks.com
Shout it