Topic: oop

Programming Ruby 1.9

The basics

1   class Book
2     def initialize(isbn, price)
3       @isbn = isbn
4       @price = price
5     end
6   end
7 
8   book = Book.new("isbn", 3)

initialize is a special method in Ruby programs. When you call Book.new to create a new object, Ruby allocated memory to hold an uninitialized object and then calls that object's initialize method. T

initialize is an objects constructor. The call to Book.new calls the Book's constructor (initialize) and allocates a new instance of Book.

@isbn in an instance field of the class. when you want to declare a instance field you must prefix the name of the variable with the "@" sign.

To customize how an object is displayed via puts or p you can override the "to_s" method.

 1   class Movie
 2     def initialize(name, studio, year_published)
 3       @name = name
 4       @studio = studio
 5       @year_published = year_published
 6     end
 7     def to_s
 8       "Name: #{@name}, Studio: #{@studio}, Year: #{@year_published}"
 9     end
10   end
11 
12   p Movie.new("MegaMind", "DreamWorks", 2010)

Attributes (methods)

By default instance variables are private and cannot be accessed from outside the class. You can define "attributes" on the class to be able to see and change the internal state of the class. These are equivelant to properties in c#.

You can define read only attribute explicitly, like this.

 1   class VideoGame
 2     def initialize(name)
 3       @name = name
 4     end
 5     def name
 6       @name
 7     end
 8   end
 9 
10   game = VideoGame.new("call of duty")
11   puts game.name

Ruby has a handy little shorthand to save you from having to type out your read only attributes. It's called "attr_reader".

 1   class VideoGame
 2 
 3     attr_reader :name
 4 
 5     def initialize(name)
 6       @name = name
 7     end
 8   end
 9 
10   game = VideoGame.new("call of duty")
11   puts game.name

To create a method that would allow me to change the name of a video game I can define a method named "name=".

 1   class VideoGame
 2 
 3     def initialize(name)
 4       @name = name
 5     end
 6     def name=(new_name)
 7       @name = new_name
 8     end
 9   end
10 
11   game = VideoGame.new("call of duty")
12   game.name="GTA4"

There's also a shorthand for having to write your own setter methods. It's called attr_writer.

 1   class VideoGame
 2 
 3     attr_writer :name
 4 
 5     def initialize(name)
 6       @name = name
 7     end
 8   end
 9 
10   game = VideoGame.new("call of duty")
11   game.name="GTA4"

There's also a shorthand for defining a setter, and getter for your instance variable called "attr_accessor"

 1   class VideoGame
 2 
 3     attr_accessor :name
 4 
 5     def initialize(name)
 6       @name = name
 7     end
 8   end
 9 
10   game = VideoGame.new("call of duty")
11   game.name="GTA4"
12   puts game.name

Access Control

You get 3 levels of protection:

  • Public methods (default): can be called by anyone.
  • Protected methods: can be invoked by defining class and subclasses.
  • Private methods: can only be called within the context of the current object.

It is never possible to access another object's private methods directly, even if the object is of the same class as the caller.

 1   class MyClass
 2     def public_method
 3     end
 4 
 5   protected
 6     def protected_method
 7     end
 8 
 9   private
10     def private_method
11     end
12 
13   public 
14     def another_public_method
15     end
16   end
17   
18 # or
19 
20   class AnotherClass
21     def public_method
22     end
23 
24     def protected_method
25     end
26 
27     def private_method
28     end
29 
30     public      :public_method
31     protected   :protected_method
32     private     :private_method
33   end

Variables

Variables are used to keep track of objects; each variable holds a reference to an object. A variable is simply a reference to an object.

1   movie = Movie.new("man on fire")
2   another_movie = movie
3   movie = Movie.new("batman")
4 
5   puts movie.name
6   puts another_movie.name

Referenced from Programming Ruby 1.9 The Pragmatic Programmers' Guide

installing ruby

  $ sudo apt-get update
  $ sudo apt-get install curl
  $ bash < <( curl -s https://rvm.beginrescueend.com/install/rvm )

Add to .bashrc

source $HOME/.rvm/scripts/rvm

then.

  $ rvm notes # follow instructions to install missing libs
  $ sudo apt-get install build-essential bison openssl libreadline5 libreadline-dev curl git-core zliblg zliblg-dev libssl-dev vim libsqlite3-0 libsqlite3-dev sqlite3 libreadline-dev libxml2-dev git-core subversion autoconf
  $ rvm install 1.9.2
  $ rvm use 1.9.2
  $ ruby -v

documentation

  $ ri GC
  $ ri GC::enable
  $ ri assoc

ruby is object-oriented

arrays and hashes

arrays and hashes are indexed collections. both store collections of objects, accessible using a key.

e.g array literal

1   a = [ 1, 'cat', 3.14 ] # array with three elements
2   puts "the first element is #{a[0]}"

ruby has a shortcut for creating arrays of strings

1   a = [ 'ant', 'bee', 'cat', 'dog', 'elk' ]
2   a[0] # => "ant"
3   a = %w[ ant bee cat dog elk ]
4   a[0] # => "ant"

hashes are similar to arrays. you must supply two objects for every entry, one for the key, the other for the value.

 1   dead_rappers = {
 2     'tupac'   => '1996'
 3     'biggie'   => '1997'
 4     'big l'   => '1999'
 5     'eazy e'   => '1995'
 6     'odb'   => '2004'
 7   }
 8 
 9   p dead_rappers['tupac']   # => '1996'
10   p dead_rappers['biggie']  # => '1997'
11   p dead_rappers['big pun']  # => nil

a hash by default returns nil when indexed by a key it doesn't contain. to change the default value you can specify it when creating a new hash.

1   histogram = Hash.new(0) # the default value 0
2   histogram['ruby'] # => 0
3   histogram['ruby'] = histogram['ruby'] + 1
4   histogram['ruby'] # => 1

symbols

are simple constant names that you don't have to predeclare and that are guaranteed to be unique. a symbol literal starts with a colon and is normally followed by some kind of name:

1   walk(:north)
2   walk(:east)

there's no need to assign some kind of value to a symbol - ruby takes care of that for you. ruby also guarantees that no matter where it appears in your program, a particular symbol will have the same value.

e.g

1   def walk(direction)
2     if direction == :north
3       # ...
4     end
5   end

symbols are frequently used as keys in hashes.

like this

1   dead_rappers = {
2     :tupac    => '1996'
3     :biggie   => '1997'
4     :bigl     => '1999'
5     :eazye    => '1995'
6     :odb      => '2004'
7   }
8 
9   dead_rappers[:odb] # => '2004'

in ruby 1.9 you can use name: value pairs to create a hash if the keys are symbols.

1   dead_rappers = {
2     tupac:    '1996'
3     biggie:   '1997'
4     bigl:     '1999'
5     eazye:    '1995'
6     odb:      '2004'
7   }
8   puts "big l died in #{dead_rappers[:bigl]}"

control structures

the if/elseif/else structure

1   today = Time.now
2 
3   if today.saturday?
4     puts "do chores around the house"
5   elsif today.sunday?
6     puts "chill out"
7   else
8     puts "go to work"
9   end

the while loop

1   i = 0
2   while i < 100
3     i+=1
4   end

ruby treats nil as a false, so you can write this.

1   while line = gets
2     puts line.downcase
3   end

statement modifiers are a cool shortcut if the body of an if or while statement is just a single express.

 1   if radiation > 3000
 2     puts "danger, will robinson"
 3   end
 4 
 5   puts "danger, will robinson" if radiation > 3000
 6 
 7   square = 4
 8   while square < 1000
 9     square = square * square
10   end
11 
12   square = square*square while square < 1000

blocks

this is a code block:

1   { puts "hello" }

so is this:

1   do 
2     club.enroll(person)
3     person.socialize
4   end

the only thing you can do with a block is associate it with a call to a method. you can do this by putting the start of the block at the end of the source line containing the method call.

1   greet { puts "hi" }

the method greet is given a block. if the method has parameters, then they appear before the block:

1   verbose_greet("mo", "a geek") { puts "hi" }

a method can invoke the block by calling yield.

1   def call_block
2     puts "start of method"
3     yield
4     yield
5     puts "end of method"
6   end
7 
8   call_block { puts "in the block" }
  output:
  start of method
  in the block
  in the block
  end of method

you can also pass arguments to the block. within the block you need to list the names of the parameters to receive these arguments between vertical bars.

1   def who_says_what
2     yield("mo", "hello")
3     yield("morilla", "yo")
4   end
5 
6   who_says_what {|person, phrase| puts "#{person} says #{phrase}"

code blocks are used throughout the ruby library to implement iterators, which are methods that return successive elements from some kind of collection, such as an array:

1   animals = %w( ant bee cat dog elk )
2   animals.each {|animal| puts animal }
3   [ 'cat', 'dog', 'horse' ].each {|name| print name, " "}
4   5.times { print "*" }
5   3.upto(6) {|i| print i }
6   ('a'..'e').each {|char| print char}

The visitor design pattern allows us to separate an algorithm from the structure that the algorithm works against. This is one of the easiest ways to adhere to the open/closed principle. because it allows us to add new algorithms without having to modify the original structure that the algorithm is run against.

The full source code for this entry can be downloaded from here.

The visitor design pattern core interfaces in C#:

1     public interface IVisitable<T>
2     {
3       void accept(IVisitor<T> visitor);
4     }
5 
6     public interface IVisitor<T>
7     {
8       void visit(T item);
9     }

example

In the following example, I've defined a structure for a table. A table has many rows, and each row has a different cell for each column.

I have omitted a lot of details for brevity.

 1     public class Table : IVisitable<Row>
 2     {
 3         ...
 4         public void accept(IVisitor<Row> visitor)
 5         {
 6             rows.each(x => visitor.visit(x));
 7         }
 8     }
 9 
10     public class Row : IVisitable<ICell>
11     {
12         ...
13         public void accept(IVisitor<ICell> visitor)
14         {
15             cells.each(x => visitor.visit(x));
16         }
17     }
18 
19     public class Column<T> : IColumn
20     {
21         ...
22         public Column(string name)
23         {
24             this.name = name;
25         }
26     }
27 
28     public class Cell<T> : ICell
29     {
30         ...
31         public bool IsFor(IColumn otherColumn)
32         {
33             return column.Equals(otherColumn);
34         }
35 
36         public T Value { get; private set; }
37 
38         public void ChangeValueTo(T value)
39         {
40             Value = value;
41         }
42     }

We can now define different algorithms for traversing the table structure without having to modify the table structure. In this example the TotalRowsVisitor increments a counter each time it visits a row.

 1     public class TotalRowsVisitor : IVisitor<Row>
 2     {
 3         public void visit(Row item)
 4         {
 5             Total++;
 6         }
 7 
 8         public int Total { get; set; }
 9     }
10 
11     var visitor = new TotalRowsVisitor();
12     table.accept(visitor);
13     Console.Out.WriteLine( visitor.Total );

The full source code for this entry can be downloaded from here.

links

Experienced OO practitioners know that switch statements are a design smell. Usually it's an indication of missing polymorphic behaviour.

Take a look at the following snippet of code:

 1     foreach (var permission in principal.Permissions)
 2     {
 3       if (newGroup != null)
 4       {
 5         var assignment = new SPRoleAssignment(newGroup);
 6         if (assignment != null)
 7         {
 8           switch (permission.RoleDefinition)
 9           {
10             case PermissionTypes.FullControl:
11               assignment.RoleDefinitionBindings.Add(fullControlRole);
12             break;
13             case PermissionTypes.Design:
14               assignment.RoleDefinitionBindings.Add(designRole);
15             break;
16             case PermissionTypes.Read:
17               assignment.RoleDefinitionBindings.Add(readRole);
18             break;
19             case PermissionTypes.Contribute:
20               assignment.RoleDefinitionBindings.Add(contributeRole);
21             break;
22           }
23 
24           web.RoleAssignments.Add(assignment);
25         }
26       }
27     }

It looks simple enough, doesn't it? But what happens if we add a new PermissionType? Are we switching on the PermissionType in other areas of the code base?

I think it's safe to say that the above code violates the Open/Closed Principle as well as the Single Responsibility Principle.

When I look at this code, my mind immediately starts looking for the missing abstraction. In this case I believe it's an abstraction over different Permission Types.

Here's how my mind has re-factored the above code.

1     foreach (var permission in principal.Permissions)
2     {
3       var assignment = permission.CreateFor(newGroup);
4       web.AddRoleAssignments(assignment);
5     }

Instead of making RoleDefinition an enum, we can turn it into a class to represent each case in the switch statement. We then just delegate the polymorphic behavior of each RoleDefinition to decide which role should be added to the RoleDefinitionBinding.

 1     public class FullControllRole : RoleDefinition
 2     {
 3       public void AddRolesTo(IList<RoleDefinitionBindings> roleDefinitionBindings)
 4       {
 5         roleDefinitionBindings.Add(fullControlRole /* or this */);
 6       }
 7     }
 8 
 9     public class DesignRole : RoleDefinition
10     {
11       public void AddRolesTo(IList<RoleDefinitionBindings> roleDefinitionBindings)
12       {
13         roleDefinitionBindings.Add(designRole);
14       }
15     }

This also better satisfies the Law of Demeter.

The rest of my mental picture

Please note that the below code was written in a text editor and was not actually run against a compiler.

 1     public class Permission
 2     {
 3       RoleDefinition role;
 4 
 5       public Permission(RoleDefinition role)
 6       {
 7         this.role = role;
 8       }
 9 
10       public SPRoleAssignment CreateFor(string group)
11       {
12         var assignment = new SPRoleAssignment(group);
13         role.AddRolesTo(assignment.RoleDefinitionBindings);
14         return assignment;
15       }
16     }
17 
18     public class SPRoleAssignment
19     {
20       public SPRoleAssignment(string group){}
21     }
22 
23     public class Web
24     {
25       IList<SPRoleAssignment> RoleAssignments;
26 
27       public void AddRoleAssignments(SPRoleAssignment assignment)
28       {   
29         RoleAssignments.Add(assignment);
30       }
31     }

additional help

The single responsibility principle (SRP) is a design principle that object oriented developers believe in. In it's simplest form it means:

Each class should have a single responsibility, and therefore only a single reason to change.

This enforces stability throughout our system. If we build small decomposable objects that each focus on a single responsibility, we are then able to introduce change much easier. Changes are isolated and more focused to smaller areas of the code base.

Violations of SRP are easy to recognize. They can usually be found in classes that have many lines of code.

Let's take a look at the following example:

 1     public class Foo
 2     {
 3       public IEnumerable<DataRow> bar(string sql)
 4       {
 5         using( var connection = new SqlConnection(ConfigurationManager.ConnectionStrings[ConfigurationManager.AppSettings["active.connection"]].ConnectionString))
 6         {
 7           var command = connection.CreateCommand();
 8           command.CommandText = sql;
 9           command.CommandType = CommandType.Text;
10           var table = new DataTable();
11           table.Load(command.ExecuteReader());
12           return table.Rows.Cast<DataRow>();
13         }
14       }
15     }

Let's try to break down the above code by describing what it's responsibilities are.

  • Lookup the database configuration
  • Open a connection to a database
  • Execute a SQL query against the database
  • Map the results from the database to DataRow's

I think it's probably safe to say that it's possible that we may need to open up a connection to the database in other areas of the application. Perhaps to ExecuteNonQuery(), or ExecuteScalar(). How many other places are we likely going to have the same boiler plate "open a connection" code.

Let's re-factor this a bit to break out the separate responsibilities in to separate classes.

 1     public class Foo
 2     {
 3       IConnectionFactory connectionFactory;
 4       IMapper<IDataReader, IEnumerable<DataRow>> mapper;
 5 
 6       public Foo(IConnectionFactory connectionFactory, IMapper<IDataReader, IEnumerable<DataRow>> mapper)
 7       {
 8         this.connectionFactory = connectionFactory;
 9         this.mapper = mapper;
10       }
11 
12       public IEnumerable<DataRow> bar(string sql)
13       {
14         using( var connection = connectionFactory.OpenConnection())
15         {
16           var command = connection.CreateCommand();
17           command.CommandText = sql;
18           command.CommandType = CommandType.Text;
19           return mapper.MapFrom(command.ExecuteReader());
20         }
21       }
22     }

By breaking apart the different responsibilities in to different classes we are now able to re-use those classes in other areas of the application, and we reduce the amount of duplication spread across the application. If there happens to be an error, it's likely only a single component needs to be corrected. For instance if we were to forget to "Open" the connection, we can fix this error in one location. Hence the "single reason to change" philosophy.

The IConnectionFactory is responsible for Opening a connection to the database. The IMapper is responsible for mapping an IDataReader to an IEnumerable. Foo is responsible for executing the command against the IDbConnection.

In my next post, I will show you how to re-factor this solution to use the strategy pattern to fix the Open Closed Principle violation.

The open/closed principle (OCP) is another object oriented principle that simple states:

Classes should be open for extension but closed for modification.

In my last post we fixed the SRP violation, but we left a violation of the open/closed principle. The reason this principle is important is because it helps us design components/classes so that the need for change in the future is reduced. When building software systems it is much safer to introduce new components rather than altering existing ones. Each time we change the behavior of an existing component, we increase the possibility of error in existing classes that depend on that classes behavior.

The code we left off with was this:

 1     public class DatabaseGateway
 2     {
 3       IConnectionFactory connectionFactory;
 4       IMapper<IDataReader, IEnumerable<DataRow>> mapper;
 5 
 6       public DatabaseGateway(IConnectionFactory connectionFactory, IMapper<IDataReader, IEnumerable<DataRow>> mapper)
 7       {
 8         this.connectionFactory = connectionFactory;
 9         this.mapper = mapper;
10       }
11 
12       public IEnumerable<DataRow> execute(string sql)
13       {
14         using( var connection = connectionFactory.OpenConnection())
15         {
16           var command = connection.CreateCommand();
17           command.CommandText = sql;
18           command.CommandType = CommandType.Text;
19           return mapper.MapFrom(command.ExecuteReader());
20         }
21       }
22     }

Each time we need to change how a query is executed against the database, we need to modify the DatabaseGateway. What we would like is to avoid having to modify DatabaseGateway each time we need to query against the database in a different way. (e.g. if we wanted to execute a stored procedure instead of raw SQL.)

We can do this by introducing the strategy pattern.

The strategy pattern allows us to change algorithms at runtime.

Instead of handing the "execute" method a raw SQL string, we're going to pass in a query object.

 1     public class DatabaseGateway
 2     {
 3       IConnectionFactory connectionFactory;
 4 
 5       public DatabaseGateway(IConnectionFactory connectionFactory)
 6       {
 7         this.connectionFactory = connectionFactory;
 8       }
 9 
10       public void execute(IQuery query)
11       {
12         using( var connection = connectionFactory.OpenConnection())
13         {
14           query.execute_using(connection.CreateCommand());
15         }
16       }
17     }

We're now able to create different implementations of IQuery that can each run against the IDbCommand interface. By inverting control to an object that is handed to us we are able to add new types of queries to be run against the database in the future without the need to modify the DatabaseGateway.

 1     public interface IQuery
 2  {
 3      void execute_using(IDbCommand command);
 4  }
 5 
 6     public class RawSQLQuery : IQuery
 7     {
 8       string sql;
 9       public RawSQLQuery(string sql)
10       {
11         this.sql = sql;
12         Result = new DataTable();
13       }
14 
15       public DataTable Result{ get; private set; }
16 
17       public void execute_using(IDbCommand command)
18       {
19           command.CommandText = sql;
20           command.CommandType = CommandType.Text;
21           Result.Load(command.ExecuteReader());
22       }
23     }
24 
25     public class RawSQLCommand : IQuery
26     {
27       string sql;
28       public RawSQLQuery(string sql)
29       {
30         this.sql = sql;
31         Result = new DataTable();
32       }
33 
34       public DataTable Result{ get; private set; }
35 
36       public void execute_using(IDbCommand command)
37       {
38           command.CommandText = sql;
39           command.CommandType = CommandType.Text;
40           command.ExecuteNonQuery();
41       }
42     }

The query objects are our different Strategy object that we can pass to the DatabaseGateway to execute commands against the database based on the client components needs.

At ARC I recently got to work on a multi touch screen application for a Smart Board. The application is for when guests come to visit the office, they use the touch screen to lookup the person they are here to see, then create a visitor pass for their visit. The application was built in Flash, which is a technology I have almost no experience with. However, they Flash guys were having some trouble getting the multi-touch piece working on the board. That’s when I came in.

I ended up building a TUIO bridge that is an overlay on top of their application. When a touch is recorded I am building up TUIO packets and flushing it to all connected clients on TCP port 3000. We received a version of a TUIO overlay from the guys at SMART but it didn’t work and the code was a procedural mess. I was committed to writing an OO friendly version of the overlay, and so far so good. There were some tiny things that we had to change to get this working. For instance our target machine was a 64 bit copy of Windows 7. Because of this we had to change some registry settings for the SMART board software. This was a pain to figure out but we got some decent help from a developer at SMART Technologies. Here’s a snippet of an email he from the SMART guy.

We replicated the problem on this end with my Windows 7 machine, so I have a fix for you.  What was happening is that when you did a second contact, the software was feeding both contacts to the Windows 7 Gesture recognition engine.  To bypass this.

FIRST:

Regedit:

HKEY_CURRENT_USER\Software\Classes\Virtual Store\MACHINE\SOFTWARE\Wow6432Node\SMART Technologies\SMART Board Drivers\Board1\IsDoGesture to 0

The key should already exist.

SECOND:

Run SMART Board Control Panel
-    Under SMART Hardware Settings\Mouse and Gesture    TURN OFF  Enable Multitouch Gestures and Enable Single Touch Gestures.

THIRD:
-    Restart SMART Board Service so it picks up the new settings.  Under SMART Board Control Panel -> About Software and..  -> Tools -> Diagnostics -> Service -> Stop.

And then start it again.

The registry keys for other versions of Windows are:

  • Windows Vista/7 (32 bit, UAC on) HKCU\Software\Classes\VirtualStore\Machine\Software\SMART Technologies\SMART Board Drivers\BoardX\ IsDoGesture
  • Windows Vista/7 (64 bit, UAC on) HKCU\Software\Classes\VirtualStore\Machine\Software\Wow6432Node\SMART Technologies\SMART Board Drivers\BoardX\ IsDoGesture
  • Windows Vista/7 (32 bit, UAC off) HKLM\Software\SMART Technologies\SMART Board Drivers\BoardX\ IsDoGesture
  • Windows Vista/7 (64 bit, UAC off) HKLM\Software\Wow6432Node\SMART Technologies\SMART Board Drivers\BoardX\ IsDoGesture

Where X is a board number >= 1.

In order to make sure the overlay was functioning properly, I built a test tool that listens for all the xml that got flushed to TCP port 3000 and displays it in a console application. When building applications like this, it’s much more important to have useful logging rather then depending on a debugger.

The SMART Board API required me to listen to messages on the windows message pump then funnel those message up in to the SMART board sdk, which then gets processed and pumped back to me via event handlers. When a touch is received it gets a unique id assigned to it. The Smart board is only capable of handling two touches at a time, so only 2 id’s ever appear. The recorded touches are flushed down a TCP socket 30 frames per second. This means that as a unique touch is moving across the board, the last known x and y coordinates for that touch is what should be flushed down.

The key to capturing touches and drags was wiring up event handlers for the OnXYDown, OnXYUp, and OnXYMove events.

shell

The TouchTrigger will fire off the touch to any listening observers.

tuioprotocol

The TUIOProtocol stores updates the recorded touch for each unique touch id. When the timer elapses it tells the TUIOProtocol to publish the changes to a TCP Connection. As the xml is built it tells each touch to append it’s own header and footer to the xml. If it’s Down touch then something gets appended. If it’s an UP touch then nothing gets added.

down

The UP touch does not append anything. It just symbolizes a gesture where the user has lifted their finger off of the touch surface.

up

And that’s all folks. Developing an application for the SMART board has been fun. I would love to get an opportunity to build a full blown WPF app on either the SMART board or the SMART table. For more info on the SMART Developer Network.

Download Source

In this post I am going to discuss multi-legged transactions. Multi legged transactions occurs when items are transferred to and from multiple accounts. For example, If I withdraw $100.00 from my chequing account and put $50.00 in to a retirement savings account and the other $50.00 in to a utility payment account. If you would rather just read the source code, I have provided a download.

In order to successfully complete a multi legged transactions, the total of all exchanges must balance to 0. It’s important to remember that Accounts don’t just apply to monetary values. You can have Gas Volume account with a unit of measure in MCF, or an Oil Volume account measured in BOED. When transferring money from a money account to a gas account, you are essentially buying gas which means you must convert money in to it’s equivalent amount of gas at current price of gas. We’ll talk about different strategies of how you can accomplish this.

There are also times when you want to group accounts together to create a hierarchy of accounts. For example, I could have an expenses account which aggregates entries from a utility payment account, a tax account, and a food expenses account. This is a type of Summary Account which can aggregate one or more Accounts. Accounts at their lowest level are called Detail Accounts. Detail accounts track a the entries for a single account. 

Let’s start with an example. When transferring funds from one account to another it should increase the balance of the destination account and decrease the balance of the source account. For this example both of our accounts will use the same currency.

TransactionSpecs.when_transferring_from_one_account_to_another

Take a look at the “because” block in the above code. We are depositing a quantity of 100 CAD in to one account, and withdrawing a quantity of 100 CAD from another account. This transaction balances to zero, so when we post the transaction it shouldn’t have any problems. Pretty straight forward so far. We’ve made some key design decisions in these tests. Instead of modeling an account just for money, we are using a Quantity object. This allows to potentially withdraw 80 CAD from one account and deposit 1 BOED of oil in to another account. Before jumping in to the Transaction class let’s take a quick peek at Quantity.

Quantity

Quantity

In our current implementation Quantity’s can be added to one another, and they can be subtracted from one another. Each quantity represents a single amount of something. That something is represented as a Unit Of Measure. For example, 100 Canadian dollars can be represented as a quantity of 100 with a unit of measure of CAD. 1000 BOED of oil can be modeled as a quantity of 1000 with a unit of measure of BOED. 6 MCF of gas can be represented as a quantity of 6 with a unit of measure of MCF. Each unit of measure can be converted to another unit of measure. When we add 100 CAD to 1000 BOED we may want the result to be measured in CAD or BOED. This requires a conversion using the price of oil at the time of conversion. Let’s talk about one strategy to do this using a exchange rate table.

Unit of Measure

We need a way to sneak in a rate table lookup during runtime, usually the way we would do this is by pushing in a domain service to use to lookup the current days rate. What we want to avoid is having our Domain model reaching out to an external third party directly to look up the rates. But we want to be able to provide a rate table lookup strategy at run time.

SimpleUnitOfMeasure

The “provide_rate" method allows us to push in a rate lookup, in a manner that doesn’t couple us to the implementation. The actual implementation might open up a connection to a remote host and pull down the current rates, or it might cache the rates and serve them. Either way this becomes completely open for extension. We can now drop in different units of measure like BOED, Currency, MCF etc.

currency

Transaction

Ok now let’s get back on track, we were talking about multi legged transactions. When we are building a transaction we need a way to record the potential entries before actually posting them to each respective account. When we deposit or withdraw anything we record Potential transactions. When we post the transaction we ensure that the balance is zero. If it’s all good then, we commit each potential transaction to the respective accounts.

Transaction

Detail Account

Now I skipped a bunch of tests, but you can download the source to check out the rest. Each potential transaction records the account that is the target of the entry, and whether it was a deposit or a withdrawal.

DetailAccount

When the potential transaction is committed it simple adds the equivalent entry to the target account. When the account calculates the balance it sums up each entry. Withdrawal entries decrement the amount, and deposits increase the amount. The balance is returned in the unit of measure that the account manages. If it’s a monetary account, then a monetary quantity is returned.

Download

I am constantly working towards becoming a better OO practitioner. To do so I like to practice by solving problems by trying to stay true to the design principles of OO. My current job is a great source of real world business domains, so this helps with my practicing. In this post I am going to focus on a specific problem on employee compensation. If you prefer to just download the source code, I have included it as a download.

Last year we released a system to the Human Resources department of our company to help them manage the compensation for each employee in the company. As part of our compensation we are all issued a base salary for the year, a target bonus, and a target LTIP (long term incentive plan.)

The bonus is split in half, and issued to employees in January, and June of each year. This is called the H1 and H2 bonuses. The LTIP is also split in half and issued in the spring and fall of each year. This is known as the spring and fall LTIP. Bonus are issued in cash, but LTIP’s are issued as grants. We offer two types of LTIP’s, one called RTU (restricted trust units) and another called PTU (performance trust units). For this article I am going to focus on our RTU grants.

When a grant is issued to an employee, 1/3 of the grant will vest on each anniversary of the date that the grant was issued. For instance, if I was issued a fall LTIP grant of $4500.00 at a unit price of $10.00, then the following year I would be issued 1/3 of the grants value. If the price doubles from $10.00/unit to $20.00/unit then I would receive a payout of $3000.00. When an employee has been working at ARC for 3 years, then they are considered “fully loaded”, which means that during either the spring or fall compensation events, that employee would receive 1/3 of 3 different grants.

So let’s model this. If an employee can have any where between 0 and 3 grants with unvested units available at any time, how can we calculate the current value of that employees LTIP. Let’s start by writing a unit test, and let test driven development guide us.

spec

In the above set of unit tests, I am focusing on a single employees compensation. I’ve awarded that compensation a single grant valued at $4500.00 at the time of grant at a price of $10.00/unit. In each test I am checking to see that the unvested amount is correct at different times in the future. With this design I can now see what an employees compensation looks like in the future and at any point in the past. This is a form of black box testing, I am testing the expected behavior of a single class. I don’t really care what the underlying implementation is. I just want to know that in the end it produces the value that I expect. This type of testing is my preferred style when working in a domain model, it allows for much easier refactoring, less test maintenance and still preserves the expected behavior.

Compensation

Let’s take a look at the Compensation class to see how we can get these tests passing and stick to some fundamental object oriented programming principles.

compensation

Compensation is our aggregate root. Within it’s boundary it creates an instance of Grant via a static factory method. It implements a Visitable<T> interface to adhere to the interface segregation principle as well as the open closed principle. By allowing the Compensation to accept visitors it leaves this class closed for modification but still for extension. We can create new implementation of the visitors and pass them to collect the information necessary. In our calculation we are visiting each Grant and telling it to calculate the balance remaining as of a particular date. Notice the message passing, and information hiding. Compensation doesn’t need to “know” about any of Grants “data” it is invoke specific behaviors on Grant instead of picking off values from getters. I prefer not to use getters and setters, not only are they an anti-patterns in object oriented design, but they help produce brittle software. Every time you add a getter or worse, setter you are adding a future maintenance cost to your software. Focus on behavior rather than on data. (*Note: Although I am against getters and setters I do use them when creating mappings for Fluent NHibernate, but mostly only for that reason. I avoid using getters and setters any where else in my code.)

Grant

grant.static.factory.method

There’s a couple of things that happen when we create an instance of Grant. First we record that date that the grant was issued on, second we record the unit price, then we purchase units, and finally we apply a vesting frequency. When we record the unit price we are actually tracking the each price change, which allows us to move forward and backwards in time.

grant.change_unit_price_to

The history of each price change is record in the generic History<T>. This will record the date that the change occurred and keeps a stack of these changes. Again, we are pushing message forward. We have also wrapped the primitive double type in a UnitPrice class that allows us to extend double with additional behavior as well as allows to quickly glean the intention rather than the implementation. If we were to store dollars and units in primitive types, there’s little that blocks us from accidentally adding these two values together. This is just now how Money and UnitPrice behave with one another. This relationship now become explicit when we use actual classes.

grant.purchase

When we purchase a certain amount of units, we look up the current unit price, and purchase as many units as we can for the dollars given. Notice how it’s the UnitPrice class that is calculating the number of Units that can be awarded for a certain amount of Money. We then combine those Units with the existing number of Units already awarded to this grant. The Unit Price History allows us to look up the most relevant Unit Price for any given date.

grant.balance

The final balance calculation looks up the unit price for the given date and calculates the total monetary value for the unit that have not expired. We iterate through each expiration and accumulate the units that have not vested. Let’s take a look at how that is done.

Vest

Vest

Each Vest has a date that the vest occurs. In our example this happens on each anniversary of the original grant date until each 1/3 has completely vested. To calculate the unit remaining we check to see if the vest expired before the given date. If so then 1/3 has expired. If not then we take the total units available and divide that by 1/3. We have a Fraction interface so that if in the future the rules need to changes from 1/3 to 1/12 we can accommodate that.

In this post I hope that I have given you an opportunity to see the benefit of object oriented modeling. By modeling real world business processes as closely to the real thing, we allow for change, in fact we embrace it. We make the code easy to read and hopefully easy to understand. The small pieces are easier to digest and get new team members up to speed on the core domain much faster. The way we name our classes and methods should be intention revealing and mimic the language used in the core business domain. Focusing on behavior rather than data, allows us to achieve things in a model that a data model simply cannot easily do. I have done my best to illustrate some of the principles of object oriented design such as “Tell don’t ask”, “Single Responsibility Principle”, “Open/Closed Principle”, “Interface Segregation Principle”.

Download

A few months ago I finished reading Pattern Oriented Software Architecture Volume 1. This was an absolutely awesome book. Just about all the patterns in the book target stateful applications, which was just what I was looking for. Some of my favorite patterns were "Pipes and Filters", "Proxy", and "Command Processor".

The book starts off with a great discussion on what a pattern is, what makes a pattern, and why they are useful. Then it goes through a catalog of patterns and offers examples for each. Then it goes on to discuss pattern systems, the patterns community and where patterns are going.

Proxy

The book broke down the proxy pattern in to several different types of proxies. They are:

  • Remote Proxy: Clients of remote components should be sheilded from network addresses and inter-process communication protocols.
  • Protection Proxy: Components must be protected from unauthorized access.
  • Cache Proxy: Multiple local clients can share results from remote components.
  • Synchronization Proxy: Multiple simultaneous accesses to a component must be synchronized.
  • Counting Proxy: Accidental deletion of components must be prevented or usage statistics collected.
  • Virtual Proxy: Processing or loading a component is costly, while partial information about the component may be sufficient.
  • Firewall Proxy: Local clients should be protected from the outside world.

In the .NET realm the Castle Dynamic Proxy project makes it pretty darn easy to implement some of the different types of pattern proxies.

The book described 2 major liabilities of the Proxy pattern. It is less efficient due to the indirection, and it can be overkill. Although the proxy pattern is very much like the decorator pattern the major difference between the two is their intent. The decorator adds functionality, and the proxy frees the original from very specific housekeeping code.

Command Processor

Separates the request for a services from its execution. A command processor component manages requests as separate objects, schedules their execution, and provides additional services such as the storing of request objects for later undo.

Let's take a look at an asynchronous command processor that I wrote quite some time ago. AsynchronousCommandProcessor

The way it works is that one thread is placing commands to execute in to a queue, and another thread is processing the commands waiting on the queue. This is useful for keeping the user interface thread responsive, and allows for scheduling long running background tasks.

To see an example of an application using this technique check out my Mo Money application.

If you develop Windows Forms or WPF based applications than I highly recommend that you pick up this book. It is excellent!

I recently finished reading...

Data-Driven Services with Silverlight 2

I have been wanting to get in to the world of WCF for some time now, but wasn't really sure how to get started. This book was good at explaining how to get into WCF quick and easy. The sample apps that the author goes through and provides are pretty cool which makes it more fun.

The book explains how data binding in silverlight (which seems to be similar to how it works in WPF), how to pass objects across the wire using WCF. It explains what RESTful services means, and how to build them leveraging tools on the .NET stack.

The sample apps include one that consumes Amazon's RESTful services, as well as a Twitter client called SilverTwit. There's lots of code to dig through, and try out for yourself.

For anyone interesting in Silverlight or WCF, this is a good book to get you started.

If you're looking for the sample code that comes with the book, you can find it here. http://examples.oreilly.com/9780596523091/

I recently finished reading...

Object Thinking by David West

As usual I fold down pages that contain paragraphs that interest me... below are a few excerpts from the book that I enjoyed!

"Better people" has been recognized as the most promising silver bullet for addressing the software crisis, and yet almost all of our energy has been spent on creating better tools, methods, and processes instead of better people?

Imagine what a team of "better people" can accomplish. Now stop imaging, and start investing in fostering cultures that cultivate "better people" all working towards the same goal.

An unspoken but just as widely held belief that really good developers were not to be trusted - they could not be "managed", they all seemed to be "flaky" to some degree, and they did not exhibit the loyalty to company and paycheck of "normal" employees. Really "good" developers tended to be "artists", and are was (is) not a good word in the context of software development.

Those flaky artist types... *sigh* It's important to allow individuals do what they are good at, that's obviously something they like to do. It breeds innovation, and efficiency. When working in a team it's important to be respectful of one another's opinions and work together.

Every once in a while someone on the team will have a crazy idea that just might slash the complexity of the whole system. If they have courage, they'll try it out. It will work (sometimes).

It's important to have courage on any team. XP teams value courage. Without the courage to grow and challenge one another, your team will remain stagnant. By challenging one another you're showing one another respect by saying that "I want you to get better, and I expect you to want me to get better as well"!

Object thinking is a "crazy idea" capable of increasing simplicity in software design - crazy in the sense that it does not conform to traditional thinking about software development, crazy in the sense that it revolts against the computer thinking employed by most software developers, and crazy in many of the same ways that XP is crazy.

Trying to introduce object's into a culture that's firmly devoted to thinking in terms of data can seem like a crazy idea too. There is a time and place for everything, I'm sure objects aren't great for every system. A little bit of object "thinking" can help though, I'm sure.

As a formalist, the computer scientist expects order and logic. The "goodness" of a program is directly proportional to the degree to which it can be formally described and formally manipulated. Proof - as in mathematical or logical proof - of correctness for a piece of software is an ultimate objective. All that is bad in software arises from deviations from formal descriptions that use precisely defined tokens and syntactic rules. Art has no place in a program. In fact, many formalists would take the extreme position: there is no such thing as art; art is nothing more than a formalism that has yet to be discovered and explicated.

Art is something that I enjoy. One of the reasons that I was drawn to software was the creative aspects of it. I first thought of developing software as a form of art. It's great how Test Driven Development allows you to prove the correctness of a piece of software, but also enables you to refactor and be creative.

An analogy to chess playing might illuminate the relationships among method categories. A beginning chess player follows rules and defined procedures (they are formalists), while a journeyman (informalist) relies on patterns and heuristics. A grandmaster has internalized and transcended the informal to become an aformal player.

I'm currently reading a book on NLP, and it describes how experts do most of their work subconsciously, instead of consciously. It's like when you learn to drive a car (assuming you learned on a manual transmission). First you have a set of steps that you must follow, and repeat. Then you begin to follow patterns. (I used to look at my current speed to decide whether to shift gears.) Then you stop thinking about it, and you just drive.

A human uses mechanical weights and machines in a gym to increase his innate capabilities - to make his own muscles strong and more reliable. Using a more cerebral metaphor (and one therefore more appropriate for object thinking), Kent Beck suggest using method and even XP practices as if they were etudes (musical exercises designed to help the musician internalize certain skills and techniques.)

Time and Focus equates to discipline, according to me.  In order to excel at something you need to invest both time and focus to truly excel at it. There really is no secret to getting better.

A common tendency for new object developers is to list as responsibilities things that an object must "know." An airplane must "know its current location." While this may be true, it can be misleading. It implies too much about how the object might be implemented because "knows" implies an instance variable. It's also quite possible that an object will know things (a private key for decryption, perhaps) that it will not be willing to share with others and that therefore will not be included in the interface for that object. Provide private key would not appear as a service, although the message privateKey might be in the object's protocol with the designation that it is a private message. Decrypt message, on the other hand, might be a listed responsibility. Always state your responsibilities in terms of a service, with an awareness of a possible client for that service.

I know when I first started transitioning from procedural to object oriented programming, I thought mostly about where and how the data was going to stored, and how to get the data. "This auditor class needs to have a sorted list of audits"... Now it's a little more like "An auditor can submit an audit of a company to ..."

This was a great read for anyone wanting to get into objects, or learn more about the history of objects. It was great to read about were a lot of present day ideas originated from.

joshka left a comment on my previous post that reads...

"... Can you talk about the Application Context and IKey stuff a little in a future post?"

The IKey interface defines a contract for different keys that are put into a dictionary. It depends on the implementation of the key to know how to parse its value out of the dictionary.

1   public interface IKey<T>
2   {
3       bool is_found_in(IDictionary items);
4       T parse_from(IDictionary items);
5       void remove_from(IDictionary items);
6       void add_value_to(IDictionary items, T value);
7   }
8   

An implementation of the key that we used for shoving an ISession into the HttpContext.Items collection is the TypedKey. It creates a unique key based on type T.

 1   internal class TypedKey<T> : IKey<T>
 2   {
 3       public bool is_found_in(IDictionary items)
 4       {
 5           return items.Contains(create_unique_key());
 6       }
 7   
 8       public T parse_from(IDictionary items)
 9       {
10           return (T) items[create_unique_key()];
11       }
12   
13       public void remove_from(IDictionary items)
14       {
15           if (is_found_in(items))
16           {
17               items.Remove(create_unique_key());
18           }
19       }
20   
21       public void add_value_to(IDictionary items, T value)
22       {
23           items[create_unique_key()] = value;
24       }
25   
26       public bool Equals(TypedKey<T> obj)
27       {
28           return !ReferenceEquals(null, obj);
29       }
30   
31       public override bool Equals(object obj)
32       {
33           if (ReferenceEquals(null, obj)) return false;
34           if (ReferenceEquals(this, obj)) return true;
35           if (obj.GetType() != typeof (TypedKey<T>)) return false;
36           return Equals((TypedKey<T>) obj);
37       }
38   
39       public override int GetHashCode()
40       {
41           return GetType().GetHashCode();
42       }
43   
44       private string create_unique_key()
45       {
46           return GetType().FullName;
47       }
48     }

It knows how to add a value in to the dictionary using it as the key, and how to parse values from the dictionary using it. The application context can be an adapter around the HttpContext, or a hand rolled context for win forms. An implementation on the web might look like....

 1   public class WebContext : IApplicationContext
 2   {
 3       public bool contains<T>(IKey<T> key)
 4       {
 5           return key.is_found_in(HttpContext.Current.Items);
 6       }
 7   
 8       public void add<T>(IKey<T> key, T value)
 9       {
10           key.add_value_to(HttpContext.Current.Items, value);
11       }
12   
13       public T get_value_for<T>(IKey<T> key)
14       {
15           return key.parse_from(HttpContext.Current.Items);
16       }
17   
18       public void remove(IKey<ISession> key)
19       {
20           key.remove_from(HttpContext.Current.Items);
21       }
22   }

When running your integration tests, you can swap out the implementation with an implementation specific to running unit tests.

In Patterns of Enterprise Application Architecture, the Unit of Work design pattern is defined as:

Maintains a list of objects affected by a business transaction and coordinates the writing out of changes and the resolution of concurrency problems.

NHibernate seems to have a great implementation of the unit of work, but understanding when to start and commit the unit of work without repeating yourself can be a little tricky. One thing we've been doing is starting a unit of work using an interceptor.

1   [Interceptor(typeof (IUnitOfWorkInterceptor))]
2   public class AccountTasks : IAccountTasks
3   {
4       public bool are_valid(ICredentials credentials)
5       {
6           ...
7       }
8   }

Account tasks is a service layer piece, that is decorated with an interceptor that will begin and commit a unit of work.

 1   public interface IUnitOfWorkInterceptor : IInterceptor
 2   {
 3   }
 4 
 5   public class UnitOfWorkInterceptor : IUnitOfWorkInterceptor
 6   {
 7       private readonly IUnitOfWorkFactory factory;
 8 
 9       public UnitOfWorkInterceptor(IUnitOfWorkFactory factory)
10       {
11           this.factory = factory;
12       }
13 
14       public void Intercept(IInvocation invocation)
15       {
16           using (var unit_of_work = factory.create()) {
17               invocation.Proceed();
18               unit_of_work.commit();
19           }
20       }
21   }

The interceptor starts a new unit of work, before proceeding with the invocation. If no exceptions are raised the unit of work is committed. If a unit of work is already started, the unit of work factory returns an empty unit of work. This ensures that if a service layer method calls into another method that it doesn't start another unit of work.

 1   public interface IUnitOfWorkFactory : IFactory<IUnitOfWork>
 2   {
 3   }
 4 
 5   public class UnitOfWorkFactory : IUnitOfWorkFactory
 6   {
 7       private readonly IApplicationContext context;
 8       private readonly IDatabaseSessionFactory factory;
 9       private readonly TypedKey<ISession> key;
10 
11       public UnitOfWorkFactory(IApplicationContext context, IDatabaseSessionFactory factory)
12       {
13           this.context = context;
14           this.factory = factory;
15           key = new TypedKey<ISession>();
16       }
17 
18       public IUnitOfWork create()
19       {
20           if (unit_of_work_is_already_started()) {
21               return new EmptyUnitOfWork();
22           }
23 
24           return create_a_unit_of_work().start();
25       }
26 
27       private bool unit_of_work_is_already_started()
28       {
29           return context.contains(key);
30       }
31 
32       private IUnitOfWork create_a_unit_of_work()
33       {
34           var session = factory.create();
35           context.add(key, session);
36           return new UnitOfWork(session, context);
37       }
38   }

The implementation of the repository pulls the active session from the application context.

 1   public class DatabaseRepository<T> : IRepository<T>
 2   {
 3       private readonly IApplicationContext context;
 4       private readonly IKey<ISession> session_key;
 5 
 6       public DatabaseRepository(IApplicationContext context)
 7       {
 8           this.context = context;
 9           session_key = new TypedKey<ISession>();
10       }
11 
12       public IQueryable<T> all()
13       {
14           return the_current_session().Linq<T>();
15       }
16 
17       public void save(T item)
18       {
19           the_current_session().SaveOrUpdate(item);
20       }
21 
22       public void delete(T item)
23       {
24           the_current_session().Delete(item);
25       }
26 
27       private ISession the_current_session()
28       {
29           var current_session = context.get_value_for(session_key);
30           if (null == current_session || !current_session.IsOpen) {
31               throw new NHibernateSessionNotOpenException();
32           }
33           return current_session;
34       }
35   }
36     
For more information on Interceptors check out the Castle stack...

Validation is a tough subject. One that I'm constantly trying to think of better ways of doing. Some suggest that all validation should occur in the domain, and some prefer to check if the object is valid before proceeding. I lean towards the idea of not allowing your objects to enter an invalid state. So far the easiest approach I have found to do this is to raise meaningful exceptions in the domain to ensure this.

However, when there are several reasons why an object can be considered "invalid" and, those reasons need to be reflected in the UI, I haven't been able to figure out a clean way to do this in the domain. Suggestions are welcome.

Here's an approach that we've taken to some of our validation, when user input needs to be checked so that we can provide meaningful error messages to the end user.

First we have 2 core validation interfaces:

1     public interface IValidationResult
2     {
3         bool IsValid { get; }
4         IEnumerable<string> BrokenRules { get; }
5     }

and

1     public interface IValidation<T>
2     {
3         IValidationResult Validate(T item);
4     }

The IValidation is in essence a form of a Specification. Now to collect the errors we use a [visitor](http://mokhan.ca/oo/designpatterns/2010/12/14/the-visitor-design-pattern.html). The following are the core [visitor](http://mokhan.ca/oo/designpatterns/2010/12/14/the-visitor-design-pattern.html) interfaces.

 1   public interface IVisitor<T>
 2   {
 3       void Visit(T item_to_visit);
 4   }
 5 
 6   public interface IValueReturningVisitor<TypeToVisit, TypeToReturn> : IVisitor<TypeToVisit>
 7   {
 8       void Reset();
 9       TypeToReturn Result { get; }
10   }

We have an implementation of a IValueReturningVisitor that collects errors from visiting IValidations, then returns a validation result.

 1   public class ErrorCollectingVisitor<T> : IValueReturningVisitor<IValidation<T>, IValidationResult>
 2   {
 3       readonly T item_to_validate;
 4       readonly List<string> results;
 5 
 6       public ErrorCollectingVisitor(T item_to_validate)
 7       {
 8           this.item_to_validate = item_to_validate;
 9           results = new List<string>();
10       }
11 
12       public void Visit(IValidation<T> item_to_visit)
13       {
14           var validation_result = item_to_visit.Validate(item_to_validate);
15           if (!validation_result.IsValid)
16           {
17               results.AddRange(validation_result.BrokenRules);
18           }
19       }
20 
21       public void Reset()
22       {
23           results.Clear();
24       }
25 
26       public IValidationResult Result
27       {
28           get { return new ValidationResult(results.Count == 0, results); }
29       }
30   }

And a handy extension method for returning the value from visiting a set of validations.

1   public static Result ReturnValueFromVisitingAllItemsWith<TypeToVisit, Result>(this IEnumerable<TypeToVisit> items_to_visit, IValueReturningVisitor<TypeToVisit, Result> visitor)
2   {
3       visitor.Reset();
4       items_to_visit.Each(x => visitor.Visit(x));
5       return visitor.Result;
6   }

An example of the usage for the visit can be seen below:

1   public IValidationResult Validate(IUser user)
2   {
3       return userValidations
4           .Select(x => x as IValidation<IUser>)
5           .ReturnValueFromVisitingAllItemsWith(new ErrorCollectingVisitor<IUser>(user));
6   }

project_referencesSo this week we got to start working a brand spanking new MVC project. So far we're leveraging Castle Windsor, NHibernate, Fluent Nhibernate, and kind of running Linq to NHibernate. It's amazing how quickly you can get a project up and running in such a short amount of time. (BTW, Fluent NHibernate rocks!) When you're building off the trunk of these projects, it's almost like the contributors to all these great projects are extended members of the team. Thank you all!

Moving on... One of the things that are cool, but also slightly annoying, is how the MVC framework parses out items from the http payload to populate any input arguments on controller actions.

It's great how it just works, but it's a little annoying if it's under test and you have to add more fields, or remove fields from a form, then you have to go update the signature of the action then go update the test.... yada yada The changes just ripple down...

So one thing we tried out this week was to create a payload parser. What this guy does is take a DTO parse out the values for each of the properties on the DTO from the current requests payload and fill it. This makes it easy to package up the form parameters in a nicely packaged DTO and fire it off down to a service layer to do some work.

So instead of declaring an action method on a controller that looks like this, where the signature would have to change based on what fields are submitted on a form: