State Pattern


State Pattern

The state pattern is a behavioral pattern that allows an object to partially change its type at runtime.  This is useful in situations where we can not change the type of a base object, but wish to represent the state of it in encapsulated classes.

Let us consider a payroll system where employees are compensated and promoted based upon their current position. 
We could use a property to store the employees current position.

    public class Employee
{
public string Name { get; set; }

public EmployeePosition Position { get; set; }

public void Promote()
{
switch (Position)
{
case EmployeePosition.JuniorDeveloper:
Position = EmployeePosition.SeniorDeveloper;
break;
case EmployeePosition.SeniorDeveloper:
Position = EmployeePosition.TechnicalLead;
break;
case EmployeePosition.TechnicalLead:
// This is as high as it goes.
break
;
}
}

public void Compensate(Accounting accounting)
{
int salary = 0;

switch (Position)
{
case EmployeePosition.JuniorDeveloper:
salary = 40000;
break;
case EmployeePosition.SeniorDeveloper:
salary = 75000;
break;
case EmployeePosition.TechnicalLead:
salary = 100000;
break;
}

accounting.Pay(this, salary);
}
}

public enum EmployeePosition
{
JuniorDeveloper,
SeniorDeveloper,
TechnicalLead
}

public class Accounting
{
public void Pay(Employee employee, int dollars)
{
// Pay the employee
}
}
This code is brittle.  Changing the EmployeePosition enum requires changing multiple methods in the Employee domain object.  The logic is spread thin and the encapsulation is non-existent.

A Better Way

A better way to do this is to use the state pattern.  With the state pattern, the EmployeePosition enum is replaced by an abstract class representing the employees current position.
    public abstract class AbstractEmploymentState
{
private readonly Employee employee;

public AbstractEmploymentState(Employee employee)
{
this.employee = employee;
}

protected virtual Employee Employee { get { return employee; } }

public abstract void Promote();

public abstract void Compensate(Accounting accounting);
}

public class Employee
{
private AbstractEmploymentState employmentState;
public string Name { get; set; }

public AbstractEmploymentState EmploymentState
{
get { return employmentState; }
set { employmentState = value; }
}

public void Promote()
{
EmploymentState.Promote();
}

public void Compensnate(Accounting accounting)
{
EmploymentState.Compensate(accounting);
}
}

public class JuniorDeveloperState: AbstractEmploymentState
{
public JuniorDeveloperState(Employee employee) : base(employee)
{
}

public override void Promote()
{
Employee.EmploymentState = new SeniorDeveloperState(Employee);
}

public override void Compensate(Accounting accounting)
{
accounting.Pay(Employee, 40000);
}
}

public class SeniorDeveloperState: AbstractEmploymentState
{
public SeniorDeveloperState(Employee employee) : base(employee)
{
}

public override void Promote()
{
Employee.EmploymentState = new TechinicalLeadState(Employee);
}

public override void Compensate(Accounting accounting)
{
accounting.Pay(Employee, 75000);
}
}

public class TechinicalLeadState: AbstractEmploymentState
{
public TechinicalLeadState(Employee employee) : base(employee)
{
}

public override void Promote()
{
// Do Nothing, this is as high as it goes for now.
}
 
public override void Compensate(Accounting accounting)
{
accounting.Pay(Employee, 100000);
}
}

public class Accounting
{
public void Pay(Employee employee, int dollars)
{
// Pay the employee
}
}
In this example, employees are compensated and promoted based upon their positions.  The domain object, Employee, delegates these actions to the AbstractEmploymentState object. 

Note how simplified the Promote and Compensate methods of Employee are:
        public void Promote()
{
EmploymentState.Promote();
}

public void Compensate(Accounting accounting)
{
EmploymentState.Compensate(accounting);
}
Adding a new state, or increasing the complexity of the logic involved in compensation and promotion of the Employees is encapsulated, leaving the design flexible.

Polymorphic Employee

Ok, so polymorphism is good.  Every OO programmer knows that, right?  So why don't we just make the Employee class polymorphic with subclasses for each position i.e. JuniorDeveloper, SeniorDeveloper, and TechnicalLead are all classes that inherit from Employee and implement the appropriate Compensate and Promote logic.

In this case, implementing the promote logic in the subclasses would be quite challenging as we can not change the type of a class at runtime.  It could be done by changing the Promote method signature to return an Employee.  The subclasses could then each implement Promote that returned an appropriate subclass of employee.  However, this solution feels contrived.  It is also more difficult to understand for a future maintenance programmer and could lead to hard to find bugs.

Another reason we may not wish to have a polymoprhic Employee class is because there may be multiple state objects in a single domain object.  What if we need not only to compensate and promote employees based upon their position, but also to assign vacation days based upon the project to which the empoloyee is currently assigned?  A situation where we needed a class for TechnicalLeadWhoIsWorkingOnProjectX arises.

Another reason to use the state pattern instead of full blown polymoprhism of the domain object is when using an ORM such as NHibernate.  NHibernate with Single Table Inheritance does not make it easy to change the type of a persistent object.  You can do with with SQL, but it's a clumbsy solution. 

Conclusions

The state pattern is a useful tool in a programmer's swiss army knife of design patterns.  It can help you avoid ugly switch statements and encapsulate domain logic in a flexible manner.

kick it on DotNetKicks.com

author: Nathan Stott | posted @ Monday, September 01, 2008 3:12 PM | Feedback (3)

Data Transfer Objects


Data Transfer Objects Pattern

Data Transfer Objects (DTOs) are a necesarry time-sink when working with SOA.  Proper SOA dictates that you must not pass domain objects across service boundaries.  In many cases, such as when using an ORM, it is extremely difficult to pass your domain objects across the service boundaries even if you choose to disreguard the SOA guidance.  Also, there may be good reasons why you do not want to make your domain objects serializable.

DTOs Defined

So what exactly are DTOs?  They are objects that have no behavior outside of accessors and mutators of their properties.  Often times DTOs line up one-to-one with domain objects as in the following example.

/// <summary>

/// Domain Object

/// </summary>

public class Company
{
private string name;
private string taxId;

public Company(string name, string taxId)
{
this.name = name;
this.taxId = taxId;
}

public string Name { get { return name; } }
public string TaxId { get { return taxId; } }
}

/// <summary>
/// Data Transfer Object
/// </summary>
public class CompanyDTO
{
public string Name { get; set; }
public string TaxId { get; set; }
}

Other times DTOs may need to carry data for a request that has no direct representation as a single object in the domain.  Consider a service that needs to expose data about a company and its owner.  Obviously the clients shouldn't have to request data about the company and then data about the owner in a separate request.  Doing so would incur the costs of two round trips, and the owner data is a part of a single logical unit as exposed by the service.

/// <summary>

/// A company
/// </summary>
public class Company
{
private string name;
private string taxId;

public Company(string name, string taxId)
{
this.name = name;
this.taxId = taxId;
}

public string Name { get { return name; } }
public string TaxId { get { return taxId; } }

public Owner Owner { get; set; }
}

/// <summary>
/// Owner of a company
/// </summary>

public class Owner
{
public Company Company { get; set; }

public string FirstName { get; set; }
public string LastName { get; set; }
}

/// <summary>
/// Data Transfer Object

/// </summary>
public class CompanyDTO
{
public string Name { get; set; }
public string TaxId { get; set; }

public string OwnerName { get; set; }
}

From Domain Object to DTO and Back Again

The assembler pattern, a subset of the mapping pattern, is used to translate DTOs to and from domain objects.



It is possible to create a reusable conventions based assembler.  I will talk more about this in the future.  For small projects, the cost of creating assemblers for the DTOs is trivial.  For larger ones, it is still worth the effort for the sake of encapsulation.

/// <summary>

/// Assembler for Company and CompanyDTO.

/// </summary>
public interface ICompanyAssembler
{
CompanyDTO Convert(Company company);
Company Convert(CompanyDTO DTO);
}

What is so useful about an object that has no behavior?

DTOs may seem like weak objects because of their lack of behavior; but this is what makes them the one object that is safe to pass across a service boundary.  A client that interacts with your service may, and often will, have a different domain from the service itself.  In fact, many different clients with many different domains may interact with your service.  It is difficult and undesirable to share the same domain model between a service and all its potential clients. 

Consider again the Company example.  Let us assume that the service we are writing is a better business bureau catalog of companies.  The domain object, Company, may include such methods as "FileComplaint" or "RevokeLicense." 

This service may be consumed by an auction site that wants to use the companies names and ratings but has no need to file complaints and does not have the ability to revoke a license.  The company domain object for the auction site will include methods such as "AddAuction" or "AssociateWithReview." 

Sharing the domain objects between the auction site and the better business bureau service would pollute both domains; not to mention the fact that they may, and in this example certainly would, have different owners who do not wish to share code bases.

Sharing DTOs, because of their lack of behavior, works fine though.  The DTOs serve as a simple, abstracted definition for the data that the service and its clients must exchange.



DTOs also insulate your service clients from changes to the domain of the service and vice versa.  You are free to change your domain objects as much as you want and leave the DTOs alone.  The assembler can simply be updated as the domain objects are updated.

If the domain objects were shared by the clients, every change to a domain object would directly impact clients, greatly increasing the costs of maintaining the service.

kick it on DotNetKicks.com

author: Nathan Stott | posted @ Saturday, August 23, 2008 11:08 PM | Feedback (2)

MVC Forms WIth Validation Open Sourced


I've set up a google code repository here for the ASP.NET MVC Forms With Validation framework I discussed in this post.

I have made some alterations to it since the post that I will review in a later posting.

Briefly, the major changes are as follows:
  1. Multiple fieldsets are now supported in the forms.
  2. I have taken the first steps towards supporting objects that contain child objects.  A 1-1 relationship is supported in the current revision.  A new fieldset is generated for each child object.
  3. Strategies have been revamped so that they no longer are mapped to types.  Now a strategy is allowed to return null if it does not want to handle a property descriptor passed to it.  If it returns null, the next strategy in the list will be tried.
Check it out.  Tell me what you think.  I am accepting patches and if you want to be a contributor, contact me through the contact form on this blog.

kick it on DotNetKicks.com

author: Nathan Stott | posted @ Sunday, August 17, 2008 4:25 PM | Feedback (1)

Forms Framework with Validation for ASP.NET MVC


Update: This project has been open sourced.  See details in this post.

Another Update: This article was written using asp.net MVC preview 4.  I will be refactoring it now that preview 5 has been released to take advantage of model binders.  More to come on that later.

One thing that is notably missing from ASP.NET MVC is a good way to handle forms and their validation.  To resolve this issue, I started on a simple forms framework this weekend.

The end goal



I don't particularly like the action filter to handle the insertion of the model as a parameter.  I would prefer it be done via windsor and interceptors; however, for the first go round I have decided to keep the castle stack out of this.  The technique could easily be adapted to use MVC Contrib's WindsorControllerFactory and interceptors so that attributes do not have to be on every action you wish to use a form helper with.  More on that later.

For those of you who want to skip the reading and get straight to the code, download the sample project.  Look at the /Home/Contact page.  Note: the sample project depends on MVC Preview 4.

The Components

  • Field - A field is the smallest unit of input and validation in a form.
  • Widget - A widget is an abstraction of HTML template text for input.
  • FormBase - Base class for form helpers.
  • ModelForm - A form auto created from a POCO model.

Widget

A widget has a name, a value, and some attributes.  The name and value properties are by default shortcuts to the name and value attributes of the widget's attribute collection.  However, this behavior is overridable in subclasses.  A widget also has a way of rendering itself as XHTML.

Field

A field has a name, a value, and a widget.  By default a field is required, and it has a publicly exposed validate method so that it can be asked to validate its value.  It also has the ability to output itself as XHTML. 

FormBase

FormBase, the base class for forms contains a collection of fields, a method to validate the fields, and a method to load the values of fields from a name value collection.  The latter facilitates the loading of data from a browser request.

The first concrete implementation of FormBase I created was ModelForm.  A ModelForm accepts a generic type argument and in its constructor takes an object of that type.  It uses this object to generate fields for the form.  The generation logic is implemented using the strategy pattern so that it is easily customizable.

Here is the strategy interface



The ModelForm registers default strategies



The constructor allows you to pass in your own strategies



With that, we have everything we need to make a form from a POCO.

Model Action Filter

One of the neatest things ASP.NET MVC does is allow you to make controllers with parameters that will be filled in from the request. 

I wanted to be able to do this with my form classes as well.

For the first go round, I decided not to use what I would prefer: Windsor and IInterceptors.  Instead I integrated the MVC way by using their action filters.

The filters give us everything we need to set the values for a parameter.  We have access to the parameters through the ActionMethod.GetParmaeters() method and we can set the parameters via the ActionParameters dictionary.

Here is the action filter



FormFactory is a simple helper class that uses a strategy pattern to create forms based upon the type passed in and a NameValueCollection.

Settings filterContext.Action

Now, this action will work!



Rendering the Form in a View

I provided three canonical methods for rendering the form:

AsDiv - renders the form with each field wrapped in a div
AsTable - render the form with each field as a table row
AsList - render the form with each field as a list item of an unordered list

I also provided a AsCustom method that allows you to specify an XElement to wrap the form fields inside of and an XElement to use as the parent for the children generated by the field instances.

If you want even more flexibility, the rendering is completely overridable by subclassing.

Rendering the form is as simple as passing it to a view and calling AsDiv() or your preferred alternative.

All output is valid XHTML.  Invalid fields receive an error class.

Rendered


Validation


Download the Sample Project
Note: the sample project depends on MVC Preview 4.

kick it on DotNetKicks.com

author: Nathan Stott | posted @ Sunday, August 10, 2008 12:08 PM | Feedback (17)

Building NHibernate From Source


Recently, on nhusers, the NHibernate users mailing list, I've seen questions from people wishing to get started building NHibernate from source.  Some people are unfamiliar with open source in the .NET world and the tools used for it, so I made this beginner level screencast about how to get started building NHibernate from source.

You can download the screencast here.

Here is a list of the prerequisites you will need to follow along:
For reference, you can find the official NHibernate document about getting started from source here.

Note: I realized after I posted this that I forgot to provide a link to the free codec needed to view this screencast.  You will need to d/l the free camstudio lossless codec (here) to view this video.  Extract the files, right click on the .inf, and select install.  You will receive a warning, but it's ok.  This is a widely used screencasting codec and you can find a lot of info about it via google.
In the future, I'm going to convert my videos to flash and stream them to make things easier all-around.
Sorry for the inconveniance.

author: Nathan Stott | posted @ Monday, August 04, 2008 8:13 AM | Feedback (2)

MVC Routing for Alternate Response Types


I'm working on my first project using asp.net MVC. 

I came across what is probably a common desire amongst MVC developers: the ability to serve a client a response type of its choice.  I wanted to do this by specifying the desired type in the URL and keeping the URLs pretty.

Here are how I wanted the routes to look:

  • /Home/Index - return HTML view
  • /Home/Index.xml - return xml view
  • /Home/Index.json - return json view
With the routing with asp.net MVC, this was simple.

I added this to RegisterRoutes after the default route in global.asax:
routes.MapRoute(
"SpecifyType",
"{controller}/{action}.{responseType}/{id}",
new { controller = "Home", action = "Index", id = "", responseType = "html" }
);
I also changed the default route to this:

routes.MapRoute(
"Default",
"{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = "", responseType = "html" },
new { action = @"\w+" }
);
Now in the controllers you can check for the desired response type as such:

string responseType = RouteData.Values["responseType"]

This could be encapsulated into a controller base class to make things cleaner.  I'll leave that to the reader.

 kick it on DotNetKicks.com

author: Nathan Stott | posted @ Tuesday, July 29, 2008 5:17 PM | Feedback (2)

NHibernate Bulk Updates/Inserts/Deletes with Named Queries


There was an interesting thread on the NHibernate users mailing list this week where Fabio Maulo advised the use of NHibernate named queries to a user who was experiencing severe performance issues with a bulk update scenario.

This is great stuff, and I have ignored named queries almost completely in the past.

using(ISession s = OpenSession()) {
using (ITransaction tx = s.BeginTransaction())
{
IQuery sql = s.GetNamedQuery("native-delete-car").SetString(0, "Kirsten");
sql.ExecuteUpdate();
tx.Commit();
}
}

That is Fabio's example of executing the named query.  This was the mapping for the query:

<sql-query name="native-delete-car">
        <synchronize table="VEHICLE"/>
        delete from VEHICLE where Owner = ?
</sql-query>

*As Fabio so helpfully pointed out in my over eagerness posting this I ignored that this is indeed a SQL statement.  The sql-query element name should've given it away I think :). 

Here's an example of an HQL one:

<query name="delete-car">
   <![CDATA[
       delete Vehicle v where v.Owner = :owner
   ]]>
</query>

note: ExecuteUpdate is currently not supported for HQL queries.  This was the only JIRA I could find about this issue.  Looks like we're waiting on Ayende to work some magic before we have this support.

It may not look very ORMish.  Some of you may be saying, "What's the point of using an ORM at all if we're just writing SQL."  Well, that's not SQL, that's HQLHQL is not as nice as the criteria API, but it's a step above straight SQL.  Also, there are some things you can express with HQL that you can not express with the Criteria API.

Castle ActiveRecord users are not left out in the cold either.  ActiveRecord can also cleanly express named queries.  Check out the castle page on ActiveRecordBaseQuery (here).

Also, the prolific Oren Eini has a post (here) about named queries.

author: Nathan Stott | posted @ Monday, July 28, 2008 2:16 PM | Feedback (2)

BooLangStudio progress


BooLangStudio is a CodePlex project to provide Visual Studio integration for the Boo language

author: Nathan Stott | posted @ Friday, July 18, 2008 9:18 PM | Feedback (0)

Syntax Teaser


Here is a taste of one of my dogfooding test cases for Mite:

Up:
    CreateTable @Document:
        Int32 @Id, { @primary : true, @identity : true }
        Guid @Uid, { @rowguid : true }
        String @Name, { @length : 55 }
        String @Description, { @length : 100 }
   
    CreateTable @CatalogNode:
        Int32 @Id, { @primary : true, @identity : true }
        Guid @Uid, { @rowguid : true }
        String @Name, { @length : 55 }
        String @Description, { @length : 100 }
        ForeignKey @Document, { @nullable : true }

Down:
    DropTable @CatalogNode
    DropTable @Document

Look at the pretty sigils.

author: Nathan Stott | posted @ Thursday, July 10, 2008 8:57 PM | Feedback (2)

Get Involved in Mite


Hi community.

Mite is looking for contributors.  We need coders, testers, documenters, evangelists, and most of all users!

Check out the projects home on google code here: http://code.google.com/p/mite-net/

If you're interested in using Mite in your own project, let me know.  I'll do everything I can to help you get started with it.

If you need to contact me, leave a comment on this blog or use the contact from on the menu on the left.

author: Nathan Stott | posted @ Wednesday, July 09, 2008 11:40 AM | Feedback (2)