Domain Driven Design Afterthoughts...
I just finished reading Jimmy Nilsson’s
Applying Domain-Driven Design and Patterns [ADDDP] book... I actually read it cover to cover, something I’ve found difficult to compel myself to do with some of the other books that have been lying around my desk for a wee while now (such as Petzold’s
“Applications = Code + Markup” – a great book to assault someone with in a dark alley)...
First off, I think this book is a pretty good, it didn’t cover a lot of new ground for me, but It’s very down to earth, which I liked, and it’s encouraged me to have a read of Evan’s and Fowler’s more definitive works on the subject too... I also liked the fact that this book does attempt to tie the whole story together, from rough sketch through to identifying the domains language, using TDD to build up your domain model and even some of the gritty integration work, including evaluating OR/M features, using NHibernate as an example, and even looks into inversion of control contains (spring sadly, it would’ve been great to have seen Castle get a mention) and finally AOP. On the down side – I think the book could’ve tackled the application of rules to your domain model a little better (I wanted to see more code) and depending on your TDD knowledge, you might find that a couple of the chapters don’t really do much for you as there’s little focus on the model so much as the key concepts of red, green, refactor...
At any rate, one thing I did keep rolling around in the back of my mind is just how Base4.Net fits into the “domain model” picture ... it’s difficult to nail down, there are plenty of mechanisms for implementing most of what you need to create a domain model, for instance:
- Inheritance, though it’s support for discriminators in user types isn’t quite up to scratch – it only works via “ItemBase” at the moment – though I think Alex James mentioned that this would be implemented at some point... and though I haven’t tried, you could roll your own in some way.
- Aggregates (through extended properties).
- Various hooks (Events) to allow for the application of custom behavior, for instance you could wire up to a BeforeSave event on a type and implement some custom validation rules... not that easy to test though .
- A reasonable query abstraction - Good query support.
- A “logical” transaction mechanism, suitable for supporting the concept of a “UnitOfWork”, though it’s explicit, rather the implicit, and based on the examples in the documentation this could be a little annoying to work with when you’re trying to persist the entire graph for an aggregate – however using a similar implementation for “UnitOfWork” as Ayende does in the Rhino.Commons library for NHibernate I’m sure I could get it all working nicely, without too much trouble.
And it sounds like I’m on to a winner... but I think what I struggle with is that the types in your schema are not really the focal point for your domain model, because they’re not POCO, unlike say a domain model implemented with NHibernate as the backing O/RM can be, you can’t enrich or decorate them with additional functionality all that easily... It’s not that you have to build your domain model this way, it’s just that’s the way I would like to do it, at least to satisfy me that I'm not being railroaded into a bad design choice – but I think it’s the small blood price you pay for letting Base4 generate the schema assemblies for you, that loss of control is also a boon in immediate productivity when you start developing apps with Base4 apps... I’ve come close while using ActiveRecord, but it’s still not the same.
So... given the restrictions I’m left to implementing additional abstractions for my domain model... which means using repositories and services for encapsulating the business logic... which, in turn, brings me to mocking...
Mocking out my Base4 Implementation...
Now, if you recall a while back I talked about my repository implementation... basically it let you do things like:
IRepository orderRepository = IoC.Resolve<>>();
Order orderForApples = new Order();
OrderLine greenOnes = new OrderLine();
OrderLine redOnes = new OrderLine();
orderForApples.OrderLines.Add(greenOnes);
orderForApples.OrderLines.Add(redOnes);
orderRepository.Save(orderForApples);
Big woop, but what I probably neglected to mention is that the repository is great for implementing a chain of generic decorators (which can be set up in your IoC container of course)... so at the bottom/base of the chain we may have our “Base4StorageRepository” and layered on top of that we might have various decorators (each injected with a dependency for the next repository in the chain) for implementing some useful concepts...
Things that spring to mind are:
- Security
- Validation
- Logging
Being able to configure these things is quite useful, and there’s little stopping you deploying additional decorators as additional assemblies for an already installed product – just throw in some additional container configuration - and it is a great deal more elegant then implementing this functionality with AOP.
But you do kind of paint yourself in a corner at the same time... this generic decorator pattern stops you from being able to decorate the repository with additional methods for implementing business level functionality (because any decorations that are applied to your base repositorty will mask out methods and properties no present in the IRepository interface)... that’s fine though, I guess we just have to write the repository off as being more of a persistence mechanism, It’s really a logical separation of concerns anyway... you can decorate a "wrapper" at the top of the chain though (and this is how Ayende does, but lets ignore that for now ;o)
So... A higher level entity for dealing with the business level concerns is required... I call mine services, that may or may not sit right with you, but it makes reasonable sense in my application – and these service are injected as dependencies of the controllers re: MVC, yeah this is a Monorail app (or at least, part of it is)...
These services often aggregate the features of multiple repositories, like this catalogue service below which deals with a simple music structure:
public class CatalogueService : ICatalogueService
{
public CatalogueService(IRepository
In this case we have a dependency on four different repositories...
For this example we have a pretty simple schema... with a child-parent relationship between Track, Release and Artist... and a Many to Many relationship between Tracks and Genres...
Track -> Release -> Artist
Track(s) <-> Genre(s)->
The catalogue service implements the business rules for dealing with the catalogue, in some cases this is no more than querying the associated repository... so for getting a list of releases for a particular artist we have this (and yeah, I know it’s pretty daft):
public PagedItemList
I say daft because it doesn’t support sorting and filtering by a query... but it’s here to illustrate a point, and until the customer actually asks for these features I’m not going to bother building them :P
At any rate, the point is not to critique the service, but instead how can we test this catalogue service without being connected to a Base4 server... and of course it’s RhinoMocks to the rescue!
Mocking with RhinoMocks...
So here’s the guts of the test in mid-refactoring ... post red-green for those sticklers for the rules ;o) (there’s still plenty yet to clean up, but it would muddy the waters a bit for this example I think...)
[Test]
public void ListReleasesForArtist()
{
Artist artist = new Artist();
PagedItemList releases = new PagedItemList(new ItemList(), 1, 10, 20);
Func callback
= delegate(ObjectQuery query, int pageNumber, int pageSize)
{
ObjectPath path = Release.Fields.Artist.ID == artist.ID;
path.AddOrderBy("Name");
Base4Assert.ArePathsEqual(path, query.Path);
Base4Assert.AreScopesEqual(new string[] { "Artist" }, query.Scope);
Assert.AreEqual(1, pageNumber, "pageNumber");
Assert.AreEqual(10, pageSize, "pageSize");
return true;
};
Expect.Call(_releaseRepository.Find(null, 1, 10)).Callback(callback).Return(releases);
_mockRepository.ReplayAll();
ICatalogueService service =
new CatalogueService(_trackRepository, _releaseRepository, _artistRepository, _genreRepository);
PagedItemList results = service.ListReleasesForArtist(artist, 1, 10);
Assert.AreSame(releases, results);
_mockRepository.VerifyAll();
}
Pretty chunky I know - but as more tests are added there will be opportunities for removing some of that duplicated effort... however the key points to take away are:
- We don’t need to have the base4 service running.
- We are actually testing the catalogue service’s interactions with the repositories, instead of relying on detecting expected side effects in the underlying storage.
- We’re verifying the object path and scope for the query, as well as paging information, and insulating ourselves from difficult to detect changes (like forgetting to apply an object scope, which may have a severe impact on performance).
Just to complete the story, the mock repository was created in the Setup (as we use it for every test case)... here's the code for it:
[SetUp]
public void SetUp()
{
_mockRepository = new MockRepository();
_trackRepository = _mockRepository.CreateMock<>
It does not stop us from incorrectly spelling an object scope I think compile time query support for ordering and scoping of an object query will help to make this a little more robust... small potatoes.
The callback in this case is a bit of a “bad smell” – there’s support in rhino mocks for parameter constraints, but the object paths and scopes are a little too complex to test using the out the box ones... though you can get surprisingly close, they are pretty powerful... but I believe you can write custom constraints yourself – which is something I’ll do for the next post (I’ve never done it before, I'm guessing it's easy) and hopefully that will reduce the complexity of these tests quite a bit, and replace the less concise anonymous delegate, and more importantly, make it easy to develop the catalogue service in a test-driven manor.
For those more observant people you may have noticed the “Base4Assert” as well – that’s a little static helper class I’m using in these tests... it’s not perfect, but it works for simple cases including things like multi-level scopes and gives meaningful failure methods like “expected scope ‘Release.Artist’ but found nothing.” Or "expected OrderBy Name Descending, but found OrderBy Name Ascending"... which can quickly narrow down problems for you, especially if your writing these tests first (which is the whole point of this exercise I feel).
Conclusion... For Now ;o)
Last thing I’ve done is to have tossed away a lot of the additional query overloads in my
original repository design in favor of just using a single ObjectQuery parameter with and without page number and page size (returning a
PagedItemList when providing a page number and page size, and returning an
IItemList when querying without them) – It makes everything a lot more... predictable, and is a lot cleaner when you start considering generic decorator implementations (10 overloads is 10 more code paths that need testing in a decorator... ) - looking towards to the future it should conceivable that a compile time query will allow you to construct the entire object query, not just the unordered path, and I’m quite happy to build these up in a few lines of code before passing them to a find method for now.
Edit (Sunday 12th):
In a similar vein, I just noticed Ayende's great MSDN article this evening - which covers that whole IRepository story, including generic decorators and most importantly the intricacies of registering and chaining these components in the windsor container... great stuff!