Topic: csharp
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.
download
Subscribe
When you subscribe to a certain type of message. your subscription is put into the publisher
assemblies subscription queue. (if you use MsmqSubscriptionStorage())
By default when you call "LoadMessageHandlers()" your assembly automatically subscribes to all messages that your assembly has handlers for.
1 bus.Subscribe(typeof(NewEmployeeHired));
Publish
When you publish a message it gets sent to all subscribers of that message type or assembly that contains that message.
1 bus.Publish<NewEmployeeHired>(x =>
2 {
3 x.Id = employee.Id;
4 x.FirstName = message.first_name;
5 x.LastName = message.last_name;
6 });
Don't publish from the web app
You should avoid doing this because it makes it difficult to scale out, and puts unnecessary load on
your web server. Also, requests that come from the web don't correspond to events have actually
happened. They are still requests, until they are processed, then they become an event.
For example, a web tier might send the "ChangeEmployeeAddress" command to the app tier. The app tier
then processes the command and changes the employees address, then publishes the
"EmployeeAddressChanged" event. In this scenario, it wouldn't have made sense to publish
"ChangeEmployeeAddress" on to the bus. Event's that happened should be published on the bus, not
requests that we intend to process.
Send
when you send a message it is sent to a specific end point. You must tell what endpoint to send the
messages to. In order to do this you must specify it in the app.config.
1 [AcceptVerbs(HttpVerbs.Post)]
2 public ActionResult new_hire(HireNewEmployee command)
3 {
4 bus.Send(command);
5 return RedirectToAction("all");
6 }
web.config
In the following configuration, we are telling nservice bus that whenever we send a message that
from an assembly called 'common.messages.dll' it should get sent to the endpoint named 'easyhr.service.queue'.
1 <configuration>
2 <configSections>
3 <section name="MsmqTransportConfig" type="NServiceBus.Config.MsmqTransportConfig, NServiceBus.Core"/>
4 <section name="UnicastBusConfig" type="NServiceBus.Config.UnicastBusConfig, NServiceBus.Core"/>
5 <section name="RijndaelEncryptionServiceConfig" type="NServiceBus.Config.RijndaelEncryptionServiceConfig, NServiceBus.Core"/>
6 </configSections>
7 <MsmqTransportConfig InputQueue="easyhr.web.queue" ErrorQueue="error" NumberOfWorkerThreads="1" MaxRetries="5"/>
8 <UnicastBusConfig>
9 <MessageEndpointMappings>
10 <add Messages="common.messages" Endpoint="easyhr.service.queue"/>
11 <add Messages="easyhr.messages" Endpoint="easyhr.service.queue"/>
12 <add Messages="it.messages" Endpoint="it.service.queue"/>
13 </MessageEndpointMappings>
14 </UnicastBusConfig>
15 <RijndaelEncryptionServiceConfig Key="gdDbqRpqdRbTs3mhdZh9qCaDaxJXl+e7"/>
16 </configuration>
Reply
When you reply to a message that was sent to you, the reply is sent to the endpoint that sent you
the original message.
replying to a message
In the example below, our handler receives a message of type GetAllUserNamesQuery from some endpoint.
When we respond by called "bus.Reply(x)" our reply gets sent back to the endpoint that contacted us
in the first place. We do not need to know which endpoint contacted us, but the endpoint who
contacted us, had to specify the location of our queue in their app.config.
1 public class GetAllUsernamesMessageHandler : IHandleMessages<GetAllUserNamesQuery>
2 {
3 IBus bus;
4 IUserRepository users;
5 IMapper mapper;
6
7 public GetAllUsernamesMessageHandler(IBus bus, IUserRepository users, IMapper mapper)
8 {
9 this.bus = bus;
10 this.mapper = mapper;
11 this.users = users;
12 }
13
14 public void Handle(GetAllUserNamesQuery message)
15 {
16 users.FindAll().MapAllUsing<User, UserCredentials>(mapper).Each(x =>
17 {
18 bus.Reply(x);
19 });
20 }
21 }
Hosting NService Bus
With NService bus you can either have your class library hosted by the NServiceBus.Host.exe or you
can self host it. Using the NServiceBus.Host.exe allows you to deploy your class library as a
windows service quite easily.
To debug and make use of the hosted solution:
1. Add a reference to NServiceBus.Host.exe to your class library.
2. Compile the library.
3. In the project properties for you class library go to the "Debug" tab and select the option that says "Start external program:"
4. Select the elipsis (...) and go to /bin/debug/NServiceBus.Host.exe for your class library.
example of how to leverage a hosted solution.
The NServiceBus.Host.exe will scan all assemblies in the same runtime directory as it looking for
types that implement certain NServiceBus interfaces. This is how your configuration get picked up.
In the example below, we created a few classes that implement certain NServiceBus interfaces. By
doing that, our configuration automatically gets picked up and is used to configure NServiceBus.
1 public class ConfigureThisEndPoint : IConfigureThisEndpoint, AsA_Publisher, IWantCustomLogging
2 {
3 public void Init() {}
4 }
5
6 public class Initialize : IWantCustomInitialization
7 {
8 public void Init()
9 {
10 var container = new WindsorContainer();
11 Configure.Instance.RijndaelEncryptionService();
12 Configure
13 .With()
14 .Log4Net()
15 .CastleWindsorBuilder(container)
16 .XmlSerializer()
17 .RijndaelEncryptionService()
18 .MsmqTransport().IsTransactional(true).PurgeOnStartup(true)
19 .MsmqSubscriptionStorage()
20 .UnicastBus().ImpersonateSender(true).LoadMessageHandlers()
21 .CreateBus()
22 .Start()
23 ;
24 }
25 }
Self Hosting NService Bus
In a web application, you wont need to have your assembly hosted by anything because it is already
hosted by ASP.NET. You will need to tell NServiceBus how your application should be configured. You
can do this by configuring the application in Global.asax.
self hosted nservice bus example
1 public class Global : HttpApplication
2 {
3 static public IBus Bus { get; private set; }
4
5 protected void Application_Start()
6 {
7 AreaRegistration.RegisterAllAreas();
8 RouteTable.Routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
9 RouteTable.Routes.MapRoute( "Default", "{controller}/{action}/{id}", new {controller = "home", action = "index", id = UrlParameter.Optional} );
10
11 Bootstrap();
12 }
13
14 static void Bootstrap()
15 {
16 var container = new WindsorContainer();
17 ControllerBuilder.Current.SetControllerFactory(new WindsorControllerFactory(container));
18
19 Bus = Configure.WithWeb()
20 .Log4Net()
21 .CastleWindsorBuilder(container)
22 .XmlSerializer()
23 .RijndaelEncryptionService()
24 .MsmqTransport().IsTransactional(true).PurgeOnStartup(true)
25 .MsmqSubscriptionStorage()
26 .UnicastBus().ImpersonateSender(true).LoadMessageHandlers()
27 .CreateBus()
28 .Start();
29 }
30 }
In the above configuration, we are telling NService Bus that the application
* is a web application ("WithWeb"),
* we want to use CastleWindsor as our inversion of control container, ("CastleWindsorBuilder")
* we want our messages to be serialized/deserialized using an XmlSerializer, ("XmlSerializer")
* we want the WireEncryptedString's to be encrypted and decrypted using the Rijndael encryption algorithm, ("RijndaelEncryptionService")
* we want our messaging communication to use MSMQ as the storage mechanism, and it should be transactional, ("MsmqTransport().IsTransactional(true)")
* we want all existing messages in the message queue to be purged at startup, ("PurgeOnStartup")
* we want to use MSMQ to manage client subscriptions. ("MsmqSubscriptionStorage")
When we tell NServiceBus to "LoadMessageHandlers" this will scan all assemblies in the runtime
directory for all classes that implement "IHandleMessages of T", and register it in to the
container. It will also subscribe to all messages of type T from the correct publisher out on the
bus.
Things to Remember
When debugging it's always important to make sure that your 'Publishers' are started first, then
your 'Subscribers'. The reason for this is, if your Subscriber starts up before the Publisher, then
it has no one to subscribe to.
As long as you have handlers that implement IHandleMessages of T then your end point will
automatically subscribe to the end point that publishes messages of T. in you app config you will
need to configure each end point the publishes messages from a certain assembly.
I use a convention of having a messages assembly per service. so each message assembly will contain
message types that is sent to the service or that it replies with, or that it publishes.
additional information
things that suck
out of the box you can't decorate your IHandleMessages implementation with an Interceptor
attribute because this creates a proxy of the handler, and when nservicebus tries to load the type
it does it based on it's actual type not on whether the class is assignable to the type.
so basically you can't use interceptors easily.
download
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.
The TouchTrigger will fire off the touch to any listening observers.
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.
The UP touch does not append anything. It just symbolizes a gesture where the user has lifted their finger off of the touch surface.

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.
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
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.
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.
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.
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.
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.
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 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
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.
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.
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.
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
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
In an attempt to further understand BDD, I chose to revise the code from my previous post after receiving some amazing advice from two people I regard highly (Scott & JP). I should state that this is my interpretation of that advice. This may or may not be the direction they were trying to guide me towards.
1 public class when_prompted_to_save_changes_to_the_project : concerns_for<SaveChangesView>
2 {
3 context c = () => { presenter = an<ISaveChangesPresenter>(); };
4
5 after_the_sut_has_been_created after = () =>
6 {
7 save_changes_window = sut;
8 save_changes_window.attach_to(presenter);
9 };
10
11 protected static ISaveChangesPresenter presenter;
12 protected static SaveChangesView save_changes_window;
13 }
14
15 public class when_the_save_button_is_pressed : when_prompted_to_save_changes_to_the_project
16 {
17 it should_save_the_current_project = () => presenter.was_told_to(x => x.save());
18
19 because b = () => save_changes_window.save_button.control_is(x => x.OnClick( new EventArgs()));
20 }
21
22 public class when_the_cancel_button_is_pressed : when_prompted_to_save_changes_to_the_project
23 {
24 it should_not_continue_processing_the_previous_action = () => presenter.was_told_to(x => x.cancel());
25
26 because b = () => save_changes_window.cancel_button.control_is(x => x.OnClick( new EventArgs()));
27 }
28
29 public class when_the_do_not_save_button_is_pressed : when_prompted_to_save_changes_to_the_project
30 {
31 it should_not_save_the_project = () => presenter.was_told_to(x => x.dont_save());
32
33 because b = () => save_changes_window.do_not_save_button.control_is(x => x.OnClick( new EventArgs()));
34 }
I hope this is slightly more soluble, then my previous post.
In the last couple of weeks I had a chance to sprinkle some of JP's syntactic sugar, all over my projects. It's amazing how much more concise my units test have become. I've had a couple of issues where I was mocking out the behavior of some Win Forms controls, but for the most part it's been an awesome experience!
I just wanted to take a moment to say Thank you JP! I am enjoying using your BDD (on steroids) extensions. If you haven't already you need to check it out here. NOW!
Maaad, maaaad props Mr. JP!
1
2
3 public class behaves_like_save_changes_view_bound_to_presenter : concerns_for<SaveChangesView>
4 {
5 context c = () => { presenter = an<ISaveChangesPresenter>(); };
6 because b = () => sut.attach_to(presenter);
7
8 static protected ISaveChangesPresenter presenter;
9 }
10
11 public class when_the_save_button_is_clicked : behaves_like_save_changes_view_bound_to_presenter
12 {
13
14 it should_forward_the_call_to_the_presenter = () => presenter.was_told_to(x => x.save());
15
16 because b = () => EventTrigger.trigger_event<Events.ControlEvents>( new EventArgs()), sut.ux_save_button);
17
18 }
19
20 public class when_the_cancel_button_is_clicked : behaves_like_save_changes_view_bound_to_presenter
21 {
22 it should_forward_the_call_to_the_presenter = () => presenter.was_told_to(x => x.cancel());
23
24 because b = () => EventTrigger.trigger_event<Events.ControlEvents>(x => x.OnClick(new EventArgs()),sut.ux_cancel_button);
25 }
26
27 public class when_the_do_not_save_button_is_clicked : behaves_like_save_changes_view_bound_to_presenter
28 {
29 it should_forward_the_call_to_the_presenter = () => presenter.was_told_to(x => x.dont_save());
30
31 because b = () => EventTrigger.trigger_event<Events.ControlEvents>( x => x.OnClick(new EventArgs()), sut.ux_do_not_save_button );
32 }
Update: I posted the wrong link up top. here's the latest link.
I took some time today to pull down the source code for SvnBridge today, and man, I was blown away. I started at Program.cs and made it to line 25 Bootstrapper.Start(). From there I went on to look at the hand rolled container, then the ProxyFactory.
In order for me to fully grasp the System.Runtime.Remoting API for creating proxies I had to re-write the code from SVN Bridge.... I just had too... it's just how I learn. It's like tracing over cartoons when you're a kid. I still do it!
In case you're interested, the attached code is the sample I put together that is derived from the source code of SvnBridge. If you haven't checked out the source for the project, you really should.
Pretty cool stuff.... Hopefully, this helps out anyone else who's just as curious
My reduced sample source code...
1 private static void Main(string[] args)
2 {
3 var marshal_mathers = new Person("marshall mathers");
4 var some_celebrity = ProxyFactory.CreateIPerson>(marshal_mathers, new MyNameIsSlimShadyInterceptor());
5
6 try
7 {
8 var name = some_celebrity.what_is_your_name();
9 name.should_be_equal_to("slim shady");
10 }
11 catch (Exception e)
12 {
13 Console.Out.WriteLine(e);
14 }
15 Console.Out.WriteLine("will the real slim shady please stand up...");
16 Console.In.ReadLine();
17 }
In my last post I briefly mentioned how we were wiring some components in to our container. The syntax looked like the following:
1 container.AddProxyOf(
2 new ReportPresenterTaskConfiguration(),
3 new ReportPresenterTask(
4 Lazy.Load<IReportDocumentBuilder>(),
5 Lazy.Load<IApplicationSettings>())
6 );
We're using Castle Windsor under the hood, but we have an abstraction over it that allows us to configure it as we like. Even switching the underlying implementation. Which we did, from our hand rolled container to Castle Windsor. The implementation of the above method looks as follows:
1 public void AddProxyOf<Interface, Target>(IProxyConfiguration<Interface> configuration, Target instance) where Target : Interface
2 {
3 var builder = new ProxyBuilder<Interface>();
4 configuration.Configure(builder);
5 AddInstanceOf(builder.CreateProxyFor(instance));
6 }
Wikipedia defines the Proxy design pattern as:
A proxy, in its most general form, is a class functioning as an interface to another thing.
To understand the ProxyBuilder implementation you can checkout JP's strongly typed selective proxies. The "AddProxyOf" method creates an instance of a proxybuilder. It then passes it to the configuration to allow it to configure the proxy builder before building the proxy. Then it registers the proxy as a singleton in to the container.
1 public interface IConfiguration<T>
2 {
3 void Configure(T item_to_configure);
4 }
5
6 public interface IProxyConfiguration<T> : IConfiguration<IProxyBuilder<T>>
7 {
8 }
In this case the proxy configuration looks like:
1 public class ReportPresenterTaskConfiguration : IProxyConfiguration<IReportPresenterTask>
2 {
3 public void Configure(IProxyBuilder<IReportPresenterTask> builder)
4 {
5 var constraint = builder.AddInterceptor<DisplayProgressBarInterceptor>();
6 constraint.InterceptOn.RetrieveAuditReport();
7 }
8 }
This guy adds a progress bar interceptor, that displays a progress bar as the report is getting generated via the "RetrieveAuditReport" method on the IReportPresenterTask.
Patterns of Enterprise Application Architecture defines Lazy Load as:
An object that doesn't contain all of the data you need but knows how to get it.
A while back I was trying to figure out how to lazy load objects from a container, so that I didn't need to depend on the objects dependencies needing to be wired up in the correct order. The syntax I was looking for was something like the following....
1 container.AddProxyOf(
2 new ReportPresenterTaskConfiguration(),
3 new ReportPresenterTask(
4 Lazy.Load<IReportDocumentBuilder>(),
5 Lazy.Load<IApplicationSettings>())
6 );
Lazy.Load will return a proxy in place of an actual implementation. This is just a temporary place holder that will forward the calls to the actual implementation. It wont load an instance of the actual type until the first time a call is made to it.
1 public class when_calling_a_method_with_no_arguments_on_a_lazy_loaded_proxy : lazy_loaded_object_context
2 {
3 [Observation]
4 public void should_forward_the_original_call_to_the_target()
5 {
6 target.should_have_been_asked_to(t => t.OneMethod());
7 }
8
9 protected override void establish_context()
10 {
11 target = dependency<ITargetObject>();
12
13 test_container
14 .setup_result_for(t => t.find_an_implementation_of<ITargetObject>())
15 .will_return(target)
16 .Repeat.Once();
17 }
18
19 protected override void because_of()
20 {
21 var result = Lazy.Load<ITargetObject>();
22 result.OneMethod();
23 }
24
25 private ITargetObject target;
26 }
So when the method "OneMethod" is called on the proxy. It should forward the call to the target, which can be loaded from the container. The implementation depends on Castle DynamicProxy, and looks like the following...
1 public static class Lazy
2 {
3 public static T Load<T>() where T : class
4 {
5 return create_proxy_for<T>(create_interceptor_for<T>());
6 }
7
8 private static LazyLoadedInterceptor<T> create_interceptor_for<T>() where T : class
9 {
10 Func<T> get_the_implementation = resolve.dependency_for<T>;
11 return new LazyLoadedInterceptor<T>(get_the_implementation.memorize());
12 }
13
14 private static T create_proxy_for<T>(IInterceptor interceptor)
15 {
16 return new ProxyGenerator().CreateInterfaceProxyWithoutTarget<T>(interceptor);
17 }
18 }
19
20 internal class LazyLoadedInterceptor<T> : IInterceptor
21 {
22 private readonly Func<T> get_the_implementation;
23
24 public LazyLoadedInterceptor(Func<T> get_the_implementation)
25 {
26 this.get_the_implementation = get_the_implementation;
27 }
28
29 public void Intercept(IInvocation invocation)
30 {
31 var method = invocation.GetConcreteMethodInvocationTarget();
32 invocation.ReturnValue = method.Invoke(get_the_implementation(), invocation.Arguments);
33 }
34 }
35
36 public static class func_extensions
37 {
38 public static Func<T> memorize<T>(this Func<T> item) where T : class
39 {
40 T the_implementation = null;
41 return () => {
42 if (null == the_implementation) {
43 the_implementation = item();
44 }
45 return the_implementation;
46 };
47 }
48 }
"resolve" is a static gateway to the underlying IDependencyRegistry. This idea was totally inspired by JP's strongly typed selective proxies. If you haven't already, you should definitely check it out.
Download the source.
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.
Recently, we've been mocking out IQueryable's as return values, which had led to setups that look like the following...
1 programs.setup_result_for(x => x.All()).Return(new List<IProgram> {active_program,inactive_program}.AsQueryable());
I just switched over to the following syntax... by creating an extension method.
1 programs.setup_result_for(x => x.All()).will_return(active_program,inactive_program);
The following are the extensions methods to make this work.
1 public static IMethodOptions<IEnumerable<R>> will_return<R>(this IMethodOptions<IEnumerable<R>> options, params R[] items)
2 {
3 return options.Return(items);
4 }
5
6 public static IMethodOptions<IQueryable<R>> will_return<R>(this IMethodOptions<IQueryable<R>> options, params R[] items)
7 {
8 return options.Return(new Query<R>(items));
9 }
and...
1 internal classQuery<T> : IQueryable<T>
2 {
3 private readonly IQueryable<T> query;
4
5 public Query(params T[] items)
6 {
7 query = items.AsQueryable();
8 }
9
10 public Expression Expression
11 {
12 get { return query.Expression; }
13 }
14
15 public Type ElementType
16 {
17 get { return query.ElementType; }
18 }
19
20 public IQueryProvider Provider
21 {
22 get { return query.Provider; }
23 }
24
25 public IEnumerator<T> GetEnumerator()
26 {
27 return query.GetEnumerator();
28 }
29
30 IEnumerator IEnumerable.GetEnumerator()
31 {
32 return GetEnumerator();
33 }
34 }
Hope, this helps!
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 }
So 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: