Jun 23, 2008 / software ~ .net
A .NET state pattern for business entities

I started playing around with some ideas for a simple implementation of the State pattern. I wanted something that would allow business entities to exist in various states, and have different validations and business logic in different states.

This implementation is a starting point. I've not applied it to anything real-world yet, so it might be completely naive. Thought I'd chuck it out there for opinions regardless!

   1:   
   2:  /// <summary>
   3:  /// An issue in an issue tracking system
   4:  /// </summary>
   5:  public class Issue : StateMachine
   6:  {
   7:      //define states applicable to this entity
   8:      State Draft;
   9:      State Raised;
  10:      State Closed;
  11:      State Cancelled; 
  12:   
  13:      //entity properties
  14:      public string Description;
  15:      public DateTime? FirstOpenedAt;
  16:      public List<string> History;
  17:   
  18:      public Issue()
  19:      {
  20:          //init allowable states and their transitions
  21:          Draft.CanBe(Raised, Cancelled).Initial();
  22:          Raised.CanBe(Closed, Cancelled);
  23:   
  24:          //init properties
  25:          History = new List<string>();
  26:      }
  27:      
  28:      //custom validations automagically run 
  29:      //during state transition from Draft to Raised
  30:      void Validate_Draft_To_Raised()
  31:      {
  32:          if( String.IsNullOrEmpty(Description))
  33:              ValidationErrors.Add("Description must be entered");
  34:      }
  35:      
  36:      public void Raise()
  37:      {
  38:          if( ChangeState(Raised) )
  39:          {
  40:              FirstOpenedAt = DateTime.Now;
  41:              History.Add("Issue was raised");
  42:          }
  43:      }
  44:      
  45:      public void Close()
  46:      {
  47:          if( ChangeState(Closed) )
  48:              History.Add("Issue was closed");
  49:      }
  50:   
  51:      public void Cancel()
  52:      {
  53:          if( ChangeState(Cancelled) )
  54:              History.Add("Issue was cancelled");
  55:      }
  56:  }

You may also like...