Sunday, February 12, 2012

DDD Kata, Part 3 (build atomic transaction manager i.e. UnitOfWork)

Pre-requisite: DDD Kata Part 2

Kata Focus
1) Work occurs in the Repository layer, which will be used to persist to and from a data store. The data store will be encapsulated behind interfaces.
2) A pre-requisite activity is to build a wrapper interface to encapsulate transaction commit/rollback, with commit and rollback occurring on Dispose().

Completed kata example on github: DDD Kata Part 3 sample code (github)

The Kata
Time goal: under 30 minutes

Repository layer
1. Create new class libraries:
  • Kata.Repository.Tests.Unit
  • Kata.Repository
2. Add a reference to the NUnit.Framework.dll in the new test library.

We will start by creating the interface to wrap transaction commits and rollbacks. For an initial, simple name, we'll use AtomicTransactionManager. In a few minutes we will refactor that to use the name of the corresponding design pattern.

Repository: AtomicTransactionManager
1. In the new Repository unit test library, create class AtomicTransactionManagerTests.cs
2. Verify that AtomicTransactionManager is instance of IAtomicTransactionManager.
3. Verify that the constructor of AtomicTransactionManager sets TransactionState property to “Is Begun”.
NOTE   You should be using Resharper's "generate-by-usage" (alt-Enter) to generate these properties and methods of the sut. However, make sure that the declared type on the sut is interface, otherwise your generate-by-usage will create class-only properties and methods. It should be creating the properties and methods on the interface.
4. Verify that Commit() method sets TransactionState property to “CommitRequested”
The actual name for this design pattern is UnitOfWork. You can read about it here: Martin Fowler, PEAA: Unit of Work
5. Refactor the class and interface you have created so far to UnitOfWork and IUnitOfWork
6. Verify that IUnitOfWork is instance of IDisposable
7. Verify that the Dispose() method sets TransactionState property to “RolledBack”.
8. Verify that calling first the Commit() method, then the Dispose() method, sets TransactionState Property to “Committed”.

Use a factory class to encapsulate the generation of the IUnitOfWork.
9. Verify that UnitOfWorkFactory is instance of IUnitOfWorkFactory.
10. Verify that IUnitOfWorkFactory.Create() returns an IUnitOfWork instance.

Part 3 of the kata is complete.

In the next kata, we will build the service layer with repository interfaces and mock objects.

Continue with DDD Kata Part 4

No comments: