Topic: tdd
Top 4 picks
jasmine
qunit
screwunit
#
other libs
helpful links
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 love being the guy to hit 1000 tests first... I guess I should check in first. doh!

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!
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: