Showing posts with label DDD. Show all posts
Showing posts with label DDD. Show all posts

Tuesday, October 28, 2008

Domain Driven Design - Knowledge Level

A recent thread on the ALT.NET forum got me thinking about KNOWLEDGE LEVEL, a seldom discussed but useful pattern from domain driven design. As with many patterns near the end of the book its a pattern that isn't going to suit every situation but it is a pattern that I think has a lot of value. In summary we aim to explicitly split our model into:

  1. Operations Level - The place that we do our day-to-day business. For example Shipment, Account.
  2. Knowledge Level - Objects that describe/constrain the objects in the basic (operations) level. For example EmployeeType, RebatePaymentMethod, ShipmentMethod.

I'm not a big fan of just repeating what's already in books and to my mind if you want to understand DDD then I'd suggest you read the DDD bible. I'm thus not going to go over the pattern, but I did think it was worth a post about what I've found when coming to the detailed design and implementation of classes in a knowledge layer. I thought I'd start by discussing how you can persist/load/model objects in the KNOWLEDGE LEVEL, moving on to other topics in later posts. Two caveats:

  1. Simple Example - Rather than using a real example I've chosen to use the shipping method example from the thread, I've never worked in that domain so this may be a bad idea but it felt right...
  2. Might seem obvious - If you are an object/behaviour first type of developer then you'll be looking at using OO techniques and so some of this will just be waffle. However I've seen situations where people used data-driven techniques when approaching their KNOWLEDGE LEVEL and so I wanted to explain why I think it's a bad idea.


Option 1 - Data First Approach

Since we store our operational objects in the database why not do the same for our KNOWLEDGE LEVEL? If we go down this path then we'd have a ShippingMethod table with one row for each shipping method we support. Of course each shipping method has different characteristics, perhaps certain shipping methods are only available to long standing customers or customers in certain countries. To support this we'll end up with extra columns in the ShippingMethod table and maybe even associations to other tables. To get the ShippingMethods from the database we'd probably use a REPOSITORY, probably making sure that the REPOSITORY is read-only (maybe not always, see pattern for information on modifying the KNOWLEDGE LEVEL).

Disadvantages

This approach obviously has disadvantages:

  1. Loss of clarity - Our ubiquitous language might refer to a "local carrier shipping method" but it won't be visible in the domain model and in fact to see details about this shipping method you need to look at the appropriate row in the ShippingMethod table. Even if you don't value the ubiquitous language this is a problem because as a developer you'll end up switching between the code and database in order to understand even simple aspects of the behaviour.
  2. Goodbye OO, hello procedural - Since there is no LocalCarrierShippingMethod class I have nowhere to put its behaviour, instead I have to fall back on a procedural style of program where we load in the data about the ShippingMethod with an ID of 3 (which happens to be the local carrier shipping method) and then look at its SupportsInternationalDelivery boolean flag before deciding how to proceed (hopelessly naive example alert). We can encapsulate this logic in a service, perhaps a ShippingMethodSelectionService but its still more than a little smelly.
  3. No explicit associations - Imagine if we know that the local carrier shipping method is only available for certain types of Orders and that the decision making also takes into account the Customer placing the Order. If we're using the database-driven approach then managing this becomes very difficult, we can't just look at our LocalCarrierShippingMethod class or at some code that sets up the associations. Instead we fall back and run a database query involving all sorts of joins.

Advantages

Those are, as I see it, the primary disadvantages of hiding this important information in the database. Ofcourse its not all bad:

  1. Consistency - Our KNOWLEDGE LEVEL is handled in the same was the rest of the domain model, loaded from the database as required. Not sure its a massive advantage though because we've explicitly chosen break out the KNOWLEDGE LEVEL its fair enough to say that the consistency has limited value.
  2. Flexibility - If we want to add a new kind of ShippingMethod we just add a row to the ShippingMethod table, no need to redeploy. That's the idea anyway, but its not always going to work especially when the related procedural code has to change.

Its also fair to say that the KNOWLEDGE LEVEL changes at a different pace to the rest of the model, we probably don't add ShippingMethods too often. However we might want to be able to change characteristics of existing ShipmentMethod's, such as changing their price (remember this probably only affects future Shipments) or changing what Countries they can be used in. So on the flexibility angle you've actually got a couple of types of changes:

  1. Adding/removing concepts -  Perhaps adding a donkey based shipment method, to me its safe to require a redeploy for this sort of change and in any case without some serious thought we're not necessarily going to be able to do just by modifying a table anyway. 
  2. Changing configuration/associations - Its maybe fair enough to expect to be able to ban using donkey based shipping for all future orders in Spain without requiring the code to be redeployed. As I'll show below this can work even if you go for an object-oriented approach and I also think this is a case where a DSL would really add value (not tried that though).

Those are the main advantages I've heard about, and as I say I'm not sold on them. That brings me on to how I think you should go about it...

 

Option 2 - Object Oriented Approach

Take that "local carrier shipping method" concept and turn it into a LocalCarrierShippingMethod class, probably inheriting from a ShippingMethod base class. There's only one instance of this class and since its read-only (at least as far as normal usage goes) it's totally safe to share it. The ShippingMethod has any data it needs to support the behaviour it contains and to support the interface that it exposes, so for example you might have an IsApplicableForSending(Shipment) with each subclass providing their own implementation.

Implementation

How does this look in practice, well one approach I've used is to a variant of the typesafe enum pattern. The following is just pseudo code to show the idea:

public abstract class ShipmentMethod
{
private static Dictionary<ShipmentMethodKind, ShipmentMethod> _shippingMethods = new Dictionary<ShipmentMethodKind, ShipmentMethod>();

static ShipmentMethod()
{
// NOTE: In practice you wouldn't do it like this but it is just an example....
_shippingMethods.Add(ShipmentMethodKind.LocalCarrier, new LocalCarrierShippingMethod());
_shippingMethods.Add(ShipmentMethodKind.DonkeyBased, new DonkeyBasedShippingMethod());
}

public IEnumerable<ShipmentMethod> GetAll()
{
return _shippingMethods.Values;
}

public ShipmentMethod GetByKey(ShipmentMethodKind key)
{
return _shippingMethods[key];
}

public abstract bool IsApplicableFor(Shipment toEvaluate);
}

public enum ShipmentMethodKind
{
LocalCarrier = 0,
DonkeyBased = 1
}

public class LocalCarrierShippingMethod : ShipmentMethod
{
public override bool IsApplicableFor(Shipment toEvaluate)
{

Don't get too hung up on the implementation, some of it is optional (e.g. ShipmentMethodKind) and it could be refractored quite a bit, I'm really just trying to show the idea not to show how to actually implement a solution.

You can see that in this case ShipmentMethod is really just a SPECIFICATION but in real situations a ShipmentMethod might well have more behaviour and data. The base class gives us an easy way to access all the ShipmentMethods that the system handles, this can be useful because it could easy provide useful methods like GetAllShipmentMethodsThatCanHandle(Shipment).

In reality there are multiple ways of implementing this, in particular you might want to load in the configuration for each ShipmentMethod from a database or other data source. This is more flexible than including it in the code but slightly more complicated to implement.

Referential Integrity

If you choose not to load the data from the database then we might seem to have a problem, how do we associate this ShipmentMethod with other objects in the KNOWLEDGE LEVEL and operational level?

It would seem that we've lost referential integrity but we have choices:

  1. Generate tables - The code in the static constructor in ShipmentMethod can be used to generate a table in the database.
  2. Use enum value as key - We can instead treat the value of the ShipmentMethodKind as a "key" in the database, automated tests will make spotting any issues really quick.
  3. Have separate config table - As I said earlier we may want to load the configuration information for each ShipmentMethod from the database, if so we have a ShipmentMethod table which resolves the problem.

In any case I haven't found this to be a major issue, by and large I don't care that my ShipmentTable has a ShipmentMethodId table which doesn't lead me anywhere as if I want to understand what's going on I go back to the domain model.


In Closing

Not sure this topic needed as much details I've put in here, really its the KNOWLEDGE LEVEL pattern that's key but I hoped that by enumerating some of the implementation choices that I've seen I'd help you make an informed decision.

Share This - Digg It Save to del.icio.us Stumble It! Kick It DZone

Thursday, October 23, 2008

What I want from an ORM

Thought I'd blog about some of the things I'd like to see in an ORM in the future, particularly to support DDD cleanly:

  1. No enforced associations - I never want to create an association in the model just to support persistence, regardless of where keys are stored. So if I want to use uni-directional associations then I should be able to do that without having to go for workarounds.
  2. Aggregate locking - Currently, with NHibernate at least, its difficult to lock an entire aggregate. For example NHibernate's optimistic concurrency approach involves applying a version to rows, however aggregates can span tables so we really want to be able to give each aggregate a shared version (coarse-grained locking approach). See coarse-grained lock pattern.
  3. Validating before saving - I'd like hooks to automatically and cleanly validate an entire aggregate before persistence.
  4. Disabling unit of work - I'd like to be able to disable my unit of work, in many cases when working with DDD the UOW becomes more of a hindrance than anything else. I really want to be 100% sure that the only way to save a Customer is through a CustomerRepository.
  5. Revalidate value objects when reloading - Value objects only validate their data in their constructors, if your ORM does not ensure that a constructor that performs the validation is also used when reloading the object then its possible to end up with an invalid Value object. This is something you definitely want to avoid. Greg Young has raised this issue a few times, including in the NHibernate forum, and made some very good points.
  6. Value objects - Choosing to view something as a value object is a design decision that you make irrespective of the underlying DB design, so whilst the NHibernate component mapping is useful it should be as powerful as the mappings used elsewhere. Unfortunately with NHibernate components don't support inheritance nicely and if your value object is stored in a separate table things get confusing.

There may be other things I'd want but those are the ones that come to mind.

Share This - Digg It Save to del.icio.us Stumble It! Kick It DZone

Wednesday, October 22, 2008

DDD and Complexity

There have been some interesting and entirely valid discussions on Twitter about the validity of DDD and about deciding when its useful and when its too complex (including good comments from Casey Charlton and Jimmy Bogard). I full agree with Casey and Jimmy and the comments, when combined with an interesting discussion on the topic at the latest ALT.NET UK discussion, let me wanting to blog about how I think DDD can be used in different types of projects.

First off I must admit that even for a simple business system I'd be thinking about using some of the patterns from DDD, in particular I think these usually have value:

  1. Aggregate
  2. Repository
  3. Service

For example I find that thinking about aggregates makes me think much more carefully about how to map those classes to the database, for example how far to cascade, which in my view is a good idea as not thinking about boundaries can lead you to some fairly annoying debugging sessions. You can take these three patterns and with a good ORM and create and map a simple domain model to a green fields database very quickly. 

Tradeoffs

Here's some of the tradeoffs we're making when using DDD on a system that it doesn't necessarily suit:

  1. Analysis/Design - We map completely skip the analysis/design and in particular the discussions with the domain expert, instead starting from our requirements and letting TDD and our own design skills guides us to the correct design.
  2. Encapsulation - We might expose everything using getters and setters and the domain may be anaemic, for example validation may be in attributes and/or use a custom framework.
  3. Design Clarity - If our primary focus is on getting going fast then we're going to have to cut some corners.  We'd bind the domain to the GUI, design it to be as easy to map to the database, make it easy to create domain objects (default constructors) and generally make tradeoffs in the quality of the domain model to make our own lives easier.
  4. Flexibility - A model that is quick to create/map/bind is not likely going to be flexible, this may or may not be a problem.
  5. Patterns - We're ignoring half the patterns in DDD, patterns that have a lot of value in a complex domain model but may not be justified when the domain is simpler/more closely bounded.

We make these tradeoffs to make our lives easier and in particular I wanted to cover two of the tradeoffs you may choose to make.

Design Clarity

If we want to be able to bind your GUI to the domain and map it to the database quickly then we can being to fray our domain model:

  1. Value objects make binding and displaying validation errors trickier.
  2. If our user interface uses wizards then the GUI will want to create domain objects early on in the wizard, possibly without giving us any meaningful data. We thus end up with default constructors or constructors with very few arguments.
  3. If we use an ORM with a unit of work it will probably fight against our need to validate aggregates before saving them.
  4. If we use an ORM we'll find it hard to version the entire aggregate.

With discipline you can make these tradeoffs whilst still maintaining a comprehensible model but there is no doubt that we are making tradeoffs.

Flexibility

We're also sacrificing flexibility, for example a lot of talk about repositories right now focuses on generic repositories. For example we'd have a Repository<T> class where T is an aggregate root and you'd have query methods on this repository that would take Linq specifications. That's going to be fine for a lot of cases but in more complex models (or where we don't control our environment fully) our repository can encapsulate complex logic, for example we should be able to ensure the following:

  1. Instances of aggregate are never deleted or they are simply archived.
  2. Instances of aggregate Y are built up from multiple data sources.
  3. Instead of mapping aggregate Z to a (legacy) DB we map some simple DTO's and then in the repository convert them to our nicely designed aggregate.
  4. Query Z is very expensive and needs to be done using SQL.

Those are all things I’ve had to be involved in when working with a moderately complex domain model and repositories helped encapsulate those details. So whilst I think generic repositories might have their place ins some systems I think you have to be aware of the choices your making.

What was the point of all this?

My point with all this is that you can get a lot of value from DDD without following it too closely, but you need to be aware of what tradeoffs your making and why. Choosing to go for a simple domain model when you have a complex problem to solve is a really bad choice and going from active record (true active record) to a real domain model is not going to be a smooth transition.

However I don't think the choice is easy, for example there's been a lot of discussion recently on whether DDD and complex models are suitable for CRUD related problems. In general I can see why using DDD on an average CRUD system is a mistake but sometimes it is worth using. For example we used DDD on a CRM system that among other things handled parties and their associations in a temporal manner. This was a complex modelling problem solved with a complex pattern but primarily we were handling CRUD (including constraints/validation) and setting the stage for other systems to use the information. Trying to do this using active record would, in my view, have been a big mistake.

So as Casey pointed out DDD is expensive and whilst it can pay off you need to do in with eyes open fully aware of the tradeoffs involved.

Share This - Digg It Save to del.icio.us Stumble It! Kick It DZone

Wednesday, August 13, 2008

Test Data Builder and Object Mother

I've been meaning to write about this topic for a while because I think correct use of these two patterns can make a big difference to tests for any moderately complex domain model.

I'm not going to discuss the details of the two patterns themselves because there's already a lot of good content out there about them (see links at end), instead I'll discuss my impressions of them.

Why Are They Needed?

For any moderately complex domain model you're going to have quite a few ENTITIES and VALUE OBJECTs and although you'd like to avoid a Web of associations you will have associations between them.

Thus when testing a Customer (ENTITY) its quite possible that you'll want to associate an Account (ENTITY) or Name (VALUE OBJECT) with it. However you don't necessarily want the creation/configuration of the Account/Name inside the test fixture:

  1. You probably want to reuse the creation code in other tests.
  2. You don't want the creation code adding complexity to the tests, complexity that the reader doesn't care about.

There are other reasons they can be useful, most of which relate to any type of Test Helper.

Application

So far my approach has been to use TEST DATA BUILDER for value objects and then OBJECT MOTHER for Entities.

VALUE OBJECTS validate in their constructor so if you try to use an OBJECT MOTHER you get a lot of methods and overloads. For example you'd have methods to create an Address with a specific Postcode, another to create it with a specific PostCode and town...it gets old very fast and that's why I think an EXPRESSION BUILDER based approach is preferable.

ENTITIES do not necessarily force you to provide all the data to them in the constructor so an OBJECT MOTHER is a good approach. I use a combination of the patterns described in the Creation Method article in the XUnit Patterns page (also see Test Helper page on same site). This works nicely because you can use a simple method on the OBJECT MOTHER to create an ENTITY (give me an active customer) and can then customize the returned Customer in the test method (for example by giving them a rejected order).

I have used TEST DATA BUILDER for ENTITIES too, in addition to OBJECT MOTHERs, however I've only done this a few times and they are quite specific. In particular these are very high level builders so they handle cases like "Give me a customer with a relationship to an account manager who works for the company Spondooliks". This case involves at least three AGGREGATES and the associations between those aggregates and we want to make that setup really readable, which either means putting it in a method in the test class or using a TEST DATA BUILDER (or both).

One thing to be careful of is relying on values of objects returned by OBJECT MOTHERs or TEST DATA BUILDERS. If you don't pass in a value and it isn't implied by the name of the members that you used then do not rely on the value in your tests because if you do they become overly fragile and complex. So if you call CreateActive on an CustomerObjectMother and don't pass in any data then its safe to assume that the returned Customer is Active but you cannot assume that the Customer has an Age of 28 (see Creation Methods).

Are They Evil?

Some argue that both patterns are evil because by creating real ENTITIES/VALUE OBJECTS you are going from writing unit tests to writing small integration tests. I'm more in agreement with Ian Cooper on this point and think its usually fine to use real domain objects in tests (within reason). However if you disagree then you can go ahead and mock out your ENTITIES but you'd still want to use TEST DATA BUILDER for your VALUE OBJECTS (see this test smell from the mockobjects guys).

We want to avoid using OBJECT MOTHER to hide design smells For example if our ENTITIES and AGGREGATEs are too large, too complex, are overly coupled, or have too many states then we could use an OBJECT MOTHER to hide the fact that these problems make the objects difficult to create. Eric Evans discussed this topic here and I handle it by trying to ensure that the OBJECT MOTHERs themselves are kept clean and simple, if they get complex I definitely consider that as a good indicate that there is something wrong with the design.

Another argument which I've heard is that OBJECT MOTHERs and BUILDERs add a lot more code to step through and make debugging tests more difficult. As it happens I rarely debug tests but if I did I either wouldn't step into the OBJECT MOTHER or BUILDER or I'd add the necessary attributes (as Greg Young does).

Object Mother Links

  1. Pattern - You can also get this PDF here.
  2. Martin Fowler
  3. Ward's Wiki
  4. Creation Methods

Test Data Builder Links

  1. Nat Pryce - Great series of articles on the pattern.
  2. Expression Builder

Several other people use slightly different approaches, for example this one is quite interesting and is a variation of the approach I've settled on.

Share This - Digg It Save to del.icio.us Stumble It! Kick It DZone

Wednesday, August 06, 2008

Domain Model Validation

This post has been sitting as a draft for a while and finally thought I should post it in response to the recent thread in the ALT.NET forum Validate Value Objects.

So here goes, I'm going to explain basically the approach to validation that I prefer, or at least the approach we used on my last DDD project.

Value Objects

A value object will validate the parameters in the constructor and should then be immutable.
If you pass invalid values to the constructor you get an exception but if you want to know the reasons that certain values are not appropriate you call a method of the form BrokenRulesPreventingConstruction(arg1, arg2, ...). You may not need this if you can are prepared to repeat the validation in another form (such as in the GUI).
Although you might use a BUILDER to create a VALUE OBJECT I prefer to keep all the validation in the constructor of the VALUE OBJECT.
It is also worth noting that value objects simplify validation, for example if a Person must have a Name then all we need to do is check that the Person has a Name as we don't need to validate the name because all Name objects are valid (whole object).

Entities

Choices

If you want to do validation within your domain you have a couple of choices:

  1. Entity or Service Based - Some people move their business logic, including validation, into the services and leave the entities as DTO's. This brings an anaemic domain model. An alternative is to make each entity responsible for some of its own validation.
  2. Attributes or Rule Classes - If you want to use attributes then you'll likely be looking at something like EViL or the Validation Application Block (or an example project like Xeva). Attributes work for simple rules, but don't handle complex or state/processed based validation well. For more complex scenarios you'll likely turn to little rule classes (which I choose to see as variations on the SPECIFICATION pattern). Some people combine attributes and custom classes but personally I prefer just to use rule classes for all cases, it does mean you can't generate the GUI validation (client side validation) but I've yet to find an approach to automatically generating client side validation that I liked so in my view if you want that validation in the GUI then you should consider writing it separately.
  3. Inject or Direct Dependency - Some people who use rule classes inject the rules into the ENTITIES. Injecting the rules adds flexibility, but just having the domain decide which rules to use is going to be enough in a lot of cases. You sometimes need to inject though and Udi Dahan's post on Generic Validation has some good points on where it does fall down, but I still think ENTITIES can handle a lot of their own validation.
  4. Immediate or Delayed - Its natural to assume that the best way to validate is to throw exception from the property setters, disallowing invalid states. This doesn't work for cross field validation or cross object validation or where the object will be temporarily invalid.  If you want a good discussion of this see this book.
  5. Notification or Event - Udi Dahan describes an event based notification pattern.
  6. Constructor - The more you validate in the constructor the better (Constructor Initialization) but it does complicate the use of the domain objects and it is only ever a partial answer. For example if an entity moves through multiple states, or is used in multiple processes then whether it is valid is contextual. I tend to use constructor arguments for immutable's, for example a business key. 

So what do we use:

  1. Entity Based - Services are certainly involved in validation but an ENTITY is responsible for its own validation and an AGGREGATE root is responsible for validating that entity AGGREGATE.
  2. Rule Classes - We evaluated attributes but they only handle very simple validation (not null, max length) well and we didn't want to have two types of validation at play so we just use rule objects.
  3. Direct Dependency - For the sorts of systems I am developing injecting rules is not necessary, I have no need to decouple an entity from its own validation rules or to vary the rules at run-time.
  4. Delayed - You can ask an ENTITY whether it is valid at any time and you can temporarily leave it invalid, this lets the higher layers manipulate the objects as they see fit but lets us ensure that once an application "transaction" is complete the object is back to being valid.
  5. Notification - We use a Notification style approach and a style where you can ask an object whether it is valid/ready to do something (and get back the notification) or you can just try to do it(which may then cause you to get an exception containing all the reasons that the operation is not possible).

Implementation

The implementation is simple but varies from case by case.

For simple cases an entity will have a GetBrokenRules method. This method will create a collection of IDomainRule objects, it then forces each rule to evaluate the object in question. When a rule fails a description of the failure is put into a separate collection of BrokenDomainRule (NOTIFICATION) objects that the GetBrokenRules method returns.

For more complex cases we have to vary the validation based on the state (as in state pattern) of the object. This doesn't really change things too much though but instead of calling GetBrokenRules you call GetBrokenRulesDisallowingTransitionTo(...) and pass in the representation of the new state (maybe an enum value).

Aggregates

An AGGREGATE root is responsible for coordinating the validation for the entire AGGREGATE, so if you ask a Customer to validate itself then it will validate the entire aggregate and return any failings.

Cross Aggregate

If a rule involves more than one AGGREGATE then it should be performed in a SERVICE. For example if we had this requirement:

Before moving a Customer to the Active state you want to ensure that the Customer itself is valid and also that it has at least one Account.

You could make the Customer responsible for this sort of validation but a better option is to move this validation into a separate SERVICE. The same goes for validation that involves multiple instances of the same class (e.g. only one Customer with a specific e-mail address).

In addition if validation requires you to call to an external resource, even a REPOSITORY, then I would move it into a SERVICE and the SERVICE coordinates the validation.

Services

As well as cross-aggregate validation SERVICES should handle any process specific validation.

Associations

Collections can manage some validation to do with associations. For example if we had this requirement:

A Customer can only have one earnings Portfolio

We've found the best way to handle this is to make the appropriate collection responsible for the validation so when you call customer.Accounts.Add(account) you get an exception if for any reason the addition is not possible (the exception tells you all the reasons it was impossible). You also have a CanAdd method so you can evaluate without raising an exception (wouldn't work if we had to worry about the effects of threads on this code).

This validation is not performed when you validate the AGGREGATE that owns the collection (Customer) because the methods that control adding/removing from the collection can ensure the collection is always valid.

Factories

Some validation only needs to be performed on creation. If this validation is complex enough then it can be worth moving it into a FACTORY, in particular if you want to perform the validation before creating the associated ENTITY.

Share This - Digg It Save to del.icio.us Stumble It! Kick It DZone

Monday, March 17, 2008

Dependency Inversion (DIP) - Where I draw the line

I was reading James Kovacs' MSDN Magazine article Tame Your Software Dependencies for More Flexible Apps. I spent some time writing some comments to put in the related blog entry but I thought I should write up my thoughts in a little more detail because I do think that my views on dependency inversion principle (DIP) differ from other peoples.

What Does DIP Give Me

First off what is DIP, if you don't know then go read Robert Martins description and/or do a search on Google because there is lots of stuff out there (including this article by Jeremy Miller).

Testing is often the underlying reason that people push for DIP. That's a big pity because it leaves people thinking that DIP is only useful for testing, which is nonsense.

So lets go back to some of the reasons Robert Martin introduced DIP:

  1. Coupling Important Logic To Details - High-level modules should not depend on low-level modules, you don't want important business code coupled to implementation details.
  2. Reuse - You want to be able to reuse your important policy/business logic in different contexts.

So how do we violate DIP, well we can easily do it by making our domain logic depend on implementation details. Put your repositories implementation in the same project as the domain logic and call those repositories from the domain and you've got it (though the repository classes do provide some encapsulation of the details). Likewise coupling your domain logic to a specific logging framework, or maybe to a specific vendors API.

So DIP is great, no doubt, an a sensible principle. However I disagree with some of the forum entries/blog posts and so on about DIP...

Issues I Have

So let me make clear again, I don't have a problem with DIP, in fact I think it is very useful. However I do have an issue with the way people describe DIP because in many cases it differs from my experience, here are the issues I have with some of the writing about it:

  1. Layering - Robert Martins got something on layering in his post Layers, Levels & DIP. For me the key layer is the domain so I focus more effort on its dependencies because I consider it a "higher" layer, therefore DIP all the way. However I'm not so worried when it comes to the Service layer, why? Well because our service layer is lightweight (as little domain logic as possible) and shallow (not likely to have a deep call stack) so deciding to inject later is an easier change than in the domain (where you might decide you need a service 6 layers deep in a call change). The point I'm making is that DIP relates to coupling between layers but indeed the amount I'm worried about coupling depends on which layer its to and from.
  2. Mocking - I've blogged about it many times before but I've come to the view that decoupling to allow me to get in Test Doubles is not always improving my design. It depends though, but I think many people assume that extracting all sorts of interfaces to mock makes for a great design but I'm not sure it does.
  3. Coupling - So I extract an interface from each repository and now my other layers can be nice and decoupled from the repository. Sure, but you have to remember that if you do change the repository it's probably not going to be by creating another subclass (an aggregate is unlikely to have 2 repositories even if you do switch ORM) but instead by modifying the existing repositories interface. In these situations the interface will need to change, so the interface hasn't really helped hidden the change from the dependent layers. Of course the discussion on interfaces is a big one and I am of course a fan of interfaces/ABC's but I think that they work best when you target their usage and take some time to design the interfaces (to suit the clients).
  4. Flexibility - The argument goes that if every service style class supports an interface then its easy to decorate them e.g. to add auditing. It is. However you have to weight it up, the chances of you needing to decorate all your repositories is unlikely, if you do you may opt for a doing it a different way (e.g. PostSharp), and even if you do decide to do it using interfaces then you can extract those interfaces and inject at that time. Of course if your code has many clients then putting the interfaces in up-front might be a good idea but in general I'm a big fan of extracting interfaces when you need them (in general) just like I'm a big fan of refactoring to patterns instead of just using design patterns.
  5. Not All Dependencies Are Equal - How worried about a dependency I am is based on where it is going from/to.
  6. Mixed Up With DI/IoC - Some people love the fact that when they use and IoC container they get to see all the dependencies in the constructor, this sort of argument can be had separately from a discussion of DIP though.
  7. Inverting Ownership - In Agile Principles Robert Martin makes it clear that a key change is to invert the ownership of the interface, so that the interface is designed specifically for the client(s). Now I've tended to find that my repositories/services are simple enough that they only have one real interface (the one they get from being a concrete class) but we have had cases where we've had them implement interfaces specifically design for their client(s).
  8. Swapping Implementation - The obvious advantage. However am I really going to remove one repository implementation and plug in another one, maybe one using another ORM. Nope, that'd be a massive change and I couldn't just do it for one repository.

Note when I discuss interfaces above I'm talking about naive interfaces, OrderRepository having an IOrderRepository interface (interface-implementation pair). If you are creating small role interfaces (ISP) and are giving the resulting interfaces more domain meaning (IOrderBook) then you are absolutely doing a good thing. Even better if the interfaces you define are customized for the specific clients. However I think that few, very few, articles on IoC/DI/DIP focus enough on these things.

So What Point Am I Making

Personally I think a lot of talk about DIP/DI/IoC misses the key point, design. Too many examples focus on details like how you configure your container and assume the natural pre-eminence of the interface approach.

I think this is a bit of a mistake, like I say I like interfaces but I am usually skeptical about the ICustomerRepository style approach because in many places I think people use that style without thinking about what real benefits they are getting.

In our case our service layer directly creates repositories/domain service layer when it needs them. This could backfire, for sure, but so far I'm not convinced that its a big mistake and if we find that it was wrong it will be relatively easy to change. Am I violating DIP when my service layer contacts a repository directly, yes. However I'm doing it with my eyes open and (I hope) with a good understanding of the consequences.

My advice would be, before going out and learning about Windsor/Binsor and the rest find out a bit more about DIP and why its useful, that way you can judge for yourself how to proceed.

Share This - Digg It Save to del.icio.us Stumble It! Kick It DZone

Tuesday, March 11, 2008

NHibernate Gotchas - Orphans and one-to-one

I'd previously posted about NHibernate Gotchas but we just came accross a big one, cascade options on one-to-one.

Essentially we'd used the cascade option "all-delete-orphan" on a which we thought was fine. NHibernate didn't complain and the schema indicated it was a valid option.

Unfortunately the cascade option was totally ignored and indeed after quite a bit of effort we found that the docs do indicate its not supported an its a known issue.

Workarounds, not sure. Deleting the one-to-one from the ISession directly is not an option for us in our POCO domain so we may need to look at other mappings.

Worth knowing anyway!

Share This - Digg It Save to del.icio.us Stumble It! Kick It DZone

Monday, February 18, 2008

BDD - What still confuses me

Although I have now begun to play with writing high level specifications with NBehave I must admit that I'm not getting much further with understanding BDD in general.

I thought I should put my questions into a blog post, I guess its more of a brain dump than anything else though.

Is BDD just better TDD?
Its tempting to view BDD as doing TDD well. In reality though there are lots of ways to practice TDD but BDD is slightly more specific, such as the way it drives for an outside-in approach.

Having said that I think you can use BDD without buying into the whole Mock Roles, Not Objects approach but it is interesting that BDD is pushing that style of working. I've tried it out and it can have advantages but unsurprisingly it also has some serious problems.

Outside In?
Outside-in can mean many things but I like the definition from XUnit test patterns. Anyway even if you do practice outside-in you don't necessarily buy fully into the approach where you start with the GUI (or slightly below) and mock your way to all your collaborators (as described at Wikipedia or Mock Rokes, Not Objects).

If you practice DDD then you probably focus on the domain early, often then using classicist style testing practices (I've blogged about this before). If you do use mocking its probably when testing services and your probably not using it to definite ISP compliant role interfaces (or maybe you are, is it working because I am interested).

I think you can also find value in outside-in testing but this time starting from the public interface to the domain/application. You can start with a high level test and then start using TDD for the details, as discussed here. Once all the code is written. That doesn't preclude you using Test Spies or Stubs where appropriate, but it does mean that you don't need to jump directly into mocking which can lead to fragile tests.

If you do believe in mockist style testing, defining collaborations and going from there, then the high level BDD tests are a good place to do it however because thats the place where you will be thinking of high level interactions between entities/services/factories and so on. Showing those interactions in the tests could have some value, though whether you extract role interfaces is another issue.

Having said all this I do think you need to be thinking about/defining the GUI at the same time as working on the domain model to avoid overcomplication. For example you may implement a complex object hierarchy in the domain when for this version of the software something simple would have done. I've been bitten by this before, but I also think that starting from the GUI and working downwards is not the way to define a domain model. In my experience you usually need to do both GUI based work and domain work early on.

There are smart people who use outside-in testing in ways that I have no experience of (see this TDD thread which was a real eye opener for me, emphasizing just how differently people tackle testing/design).

High Level or All Levels?
For me the most exciting idea is writing high level BDD tests for two primary reasons:

  1. Stories - Lower level tests are less likely to be driven by stories from the stakeholder.
  2. Refactoring - High level tests are the ones that will provide benefits because they will be more immune to refactoring.
So can you use the same style for lower level specifications, I guess so but I haven't tried it yet and I'm not sure that it will work quite as well. If you do use it for your lower level specifications then I'd question whether a framework like NBehave is the best choice:

listStory
.AsA("developer")
.IWant("my list to behave correctly when items are added")
.SoThat("I can use it in my software");
This obviously isn't how you'd do it, but I'd be thinking that if you do use BDD at this low level then you are perhaps better just writing BDD tests without using something like NBehave (as shown on the wikipedia article of ListTest and by Jimmy Bogard in Converting tests to specs is a bad idea).

Can you use BDD for infrastructure/integration work?
NOTE: Here I'm talking about higher level (Scenarios, or Application Examples) specifications.

Ultimately everything you do is user driven but some problems make it difficult to tie your work back to a story.

For example my current project is an integration with an external system. This is quite a lot of work and defining user stories can be tricky as the users are not going to be interested till the integration is complete. Thanks to some brilliant help on the XP forum, not least Simon Jones' post, I've managed to get user stories to work for such a task but it does involve a little bit of work.

However for such a project do BDD tests make sense? Take the current piece of this project, a Windows Service that the users don't even directly use. I'm trying to use NBehave specifications but it can get a little odd, for example using the NBehave syntax who do I specify in the "As A" part of the story? Really the users don't even care that the service exists, but to be fair for this sort of work I'm happy to think outside the box a little and I think thats fine.

So yes I do think high level specifications can work for infrastructure/integration tasks.

Based On User Stories?
We use user stories and so the idea of writing the high level specifications based on user stories is attractive and I think it is a valid approach.

It is worth noting that whilst behaviour-driven.org seems to indicate that use cases are a good source whats-in-a-story does explain that its just as applicable where other requirements techniques are used (which is to be expected).

BDD and the Ubiquitous Language
I originally thought that BDD aimed to define, or help in defining, the (DDD) ubiquitous language. Its hard to know though so lets look at how BDD is linked to a ubiquitous language in some of the main articles:

  1. Wikipedia - "Behavior-driven developers use their native language in combination with the ubiquitous language of Domain Driven Design". I have no idea what this means, is it using the DDD ubiquitous language in the tests or are we saying that BDD is forming ubiquitous language for writing specificatons?
  2. Introducting BDD -Here BDD is the "ubiquitous language for the analysis process itself".
  3. Whats in a story -No mention.
  4. behaviour-driven.org - "It aims to help focus development on the delivery of prioritised, verifiable business value by providing a common vocabulary (also referred to as a UbiquitousLanguage) that spans the divide between Business and Technology.". This seems to indicate that your BDD specifications are supposed to look use the ubiquitous language.

As far as I can see there is absolutely no consistency in what the different sources of BDD mean when they talk about the ubiquitous language. I also think that taking the term ubiquitous language and using it outside of the context that DDD provides is unnecessarily confusing.

So what if the specifications are written in the ubiquitous language?

NOTE: This discussion only really applies to the higher level tests against your domain model, I don't think lower level (implementation detail) or infrastructure tests are going to be written in the ubiquitous language.

As discussed before according to behaviour-driven.org BDD:

...aims to help focus development on the delivery of prioritised, verifiable business value by providing a common vocabulary (also referred to as a UbiquitousLanguage) that spans the divide between Business and Technology."...

This sounds good and if I'm writing the tests then I will use the ubiquitous language. However if I'm doing BDD properly then I'll have others involved:

  1. BDD Process - "A SubjectMatterExpert (typically a business user) works with a BusinessAnalyst to identify a business requirement"
  2. Whats in a story - "the stories are the result of conversations between the project stakeholders, business analysts, testers and developers. BDD is as much about the interactions between the various people in the project as it is about the outputs of the development process."
So my question here is whether I'm expecting my user stories text to be written by people outside the development team? If so is it the users or the domain experts? If it's the former then I do not expect them to be in the ubiqutous language, if its the latter then I would.

As discussed above my own view is that in many cases user stories will feed into the BDD specifications. So do I expect user stories to be written in the ubiquitous language, not really and for these reasons:

  1. Different Audiences - Our users are not necessarily our domain experts and even if some of them are we probably have some who are not. Having domain experts write the user stories is not good (been there, done that) and having the users define the domain model is no better (too simplified). I thus think that expecting the users to understand the ubiquitous language, which probably has little to do with their day to day job, is unreasonable.
  2. Clutter - Stories are there to specify the behavior the user wants. With this in mind I'm not sure that cluttering them with domain model details is any more useful than including GUI details in them. Does a user care what model you put in place, probably not and I'm not sure we should expect them to.
  3. Evolving Language - You are also likely to evolve your ubiquitous language as you learn more about the domain, probably resulting in it becoming more complex. The question would then be whether you build this complexity into the user stories, I'd argue that doing so will just confuse things.

Thats the way I see it for user stories and offhand I can't think why this wouldn't apply equally to BDD. So I'm not seeing BDD affecting our ubiquitous language all that much, I think instead when writing user stories we should aim to use the language of the users.

Obviously if your domain experts are involved in writing the BDD specifications then using the ubiquitous language will be more attractive.

Anyway Greg Young has two superb posts on this namely BDD and the Shared Language and BDD and the Shared Language: The Stakeholder.

So In Conclusion...

BDD is many things to many people and although some people are trying to tie it down I'm not sure it will work.

Unfortunately although I think it is positive that there are so many ways to describe BDD I do find that in some cases (ubiquitous language) it is unnecessarily confusing.

Share This - Digg It Save to del.icio.us Stumble It! Kick It DZone

Friday, February 15, 2008

TypeMock - Allows Me Not To Decouple Too Far

I just had a situation today that emphasized to me why TypeMock can be so useful.

Design

IDomainChangeTrackingService interface in a domain assembly implemented by an infrastructure service class (DomainChangeTrackingService) in another assembly. We use DI with a ServiceLocator to get the implementation of the service into the domain.
Initially the DomainChangeTrackingService just persists the DomainChangeMessages passed to it, so all it does is call out to the DomainChangeMessageRepository:

public class DomainChangeTrackingService : IDomainChangeTrackingService
{
public void ProcessMessage(DomainChangeMessage message)
{
new DomainChangeMessageRepository().Save(message);
}
}
Testing

I've already written integration tests for the DomainChangeMessageRepository so when testing the DomainChangeTrackingService a single interaction test that just checks it calls the DomainChangeMessageRepository would be enough.

The problem was that DomainChangeTrackingService creates and uses the DomainChangeMessageRepository.

Without TypeMock I'd probably have handled this with more decoupling. I'd probably have made the repository implements an interface and the implementation of that interface is injected into DomainChangeTrackingService (or it could get it from the service locator).

This could be useful in the future but I'm certainly not wanting to worry about it right now and certainly isn't decoupling I'd be looking for. For me this is one the situations where TypeMock is great, I can interaction test DomainChangeTrackingService without having to change my design.

Share This - Digg It Save to del.icio.us Stumble It! Kick It DZone

Wednesday, February 13, 2008

Domain Oriented Messages

Greg Young has a great post titled Mocks are a code smell.

As he explains the title is to grab your attention and although he does see mocking being overused, which is definitely my view and seemed to be the general feeling at the mocking session ALT.NET UK, the post itself covers a very interesting way of handling communication within the domain.


To be honest Greg's ideas and implementations of this pattern are more advanced than mine, and I know he uses it a lot more in his designs that I do, so I'm looking forward to reading his other posts on this topic.

Trying It Out - Start Simple

If you're daunted by the idea of going to a messaging approach then you could always start simple.

As an example I would say that what Greg is suggesting is just a more advanced version of the approach that I intend to use for dirty tracking within our domain. Messages are generated when domain events happen and these will be registered with a service that you get from a service locator.

This makes testing simple as you can just use a test spy (same approach as Greg seems to be using) but is also a design that I like in terms of lowering coupling.

Share This - Digg It Save to del.icio.us Stumble It! Kick It DZone

Wednesday, February 06, 2008

Object-Object Mapping

We're starting to do a lot of mapping between domain classes and other forms, so far mainly so that we can export representations of our domain objects to external systems.

Performing the mapping quickly becomes a real pain and testing the mappings is even worse.

I don't think there is much you can do about the dullness of the testing, but I have been looking for a framework that will make the mapping easier and on an ALT.NET thread on the topic someone suggested I look at a little library called Otis.

So far I'm very impressed so here's what I've found. If you want to know more download the binaries or source code, the advantage of the source code is that it has a sample with it. The WIKI also has good information but I wanted to write what I've found so far, mainly to remind myself.

Mapping Files

I think I'm going to use the XML file approach as its cleaner, I've name the files "*.otis.xml" and made them "Embedded Resources". I also setup the XSD that you get with the binaries to give me intellisense which is very useful.

Lets look at a simple example:This shows the following:

  1. UserEntity.Id -> UserDTO.Id
  2. UserEntity.UserName -> UserDTO.TheUserName
  3. UserEntity.Advisor -> UserDTO.Advisor.Name

As you can see the mapping is written from the standpoint of the source class, once you get this its quite easy to follow.

You can read more about the mappings here but the sample with the source code is also good.

Configuration

To get the same to work I had to using the following C# code:

Configuration cfg = new Configuration();
cfg.AddAssemblyResources(Assembly.GetExecutingAssembly(), "otis.xml");

IAssembler dtoFromEntityAssembler = cfg.GetAssembler();

UserEntity entity = new UserEntity(5, "Bob Dole", "bdole");
entity.Advisor.Name = "sdaddds232";

UserDTO dto = dtoFromEntityAssembler.AssembleFrom(entity);
This allows me to do a one-way mapping from the UserEntity to the UserDTO.

Share This - Digg It Save to del.icio.us Stumble It! Kick It DZone

Tuesday, February 05, 2008

AOP and the Domain - Aspects of Domain Model Management

Finally got round to reading Mats Helanders InfoQ post Aspects of Domain Model Management.

The article is very long, with a lot of content being around hacky solutions to the problems that the author is delaing with (attaching non-business logic to the domain).

I read all of the article but if you get bored you can skip most of the middle bit right up to Using "Aspect Oriented Programming".

The bit on proxies is interesting, if you're using NHibernate then you are already using the Infrastructural Proxy Subclass approach for lazy-loading (and collections) so you should be familiar with it. However trying to use that approach to handle your own requirements is not going to be clean or transparent.

Back to AOP. The author uses his own NAspect framework for run-time AOP however we were thinking of using PostSharp as compile time seemed good enough and it is more transparent. Having to use abstract factory, or just factories, for all object creation just does not appeal though.

The attribute based approach is cool though, and its similiar to the way you attach behavior with PostSharp . All in all I think I'm going to plow on with PostSharp and then see how it goes (as described in my post AOP and the Domain - Dirty Tracking).

Share This - Digg It Save to del.icio.us Stumble It! Kick It DZone

Saturday, February 02, 2008

Test Spy - Replacing Services When Testing The Domain

At the recent discussion of mocking at ALT.NET UK we discussed using test spies.

We actually make good use of test spies now and they have some advantages. Let me give you an example where they come in handy. Our domain classes occassionally need to contact external services, interfaces implemented by these services are put in the domain (seperated interface) with the implementations available to the domain using a Service Locator.

What do to when testing though, we have maybe 1% of the the tests where we need to setup a mock version of the service and the rest don't care about the service so they can run with a do-nothing stub.

However if we register a mock version of the service with the Service Locator and if we forget to cleanup propely then that mock service will affect other tests. Its also painful having to put the stub service back in after you are doing using the mock.

The solution, suggested by one of my colleagues, is simple. We don't ever mock the service but instead we use a test spy. We register the Test Spy with the Service Locator in a method tagged with AssemblyInitializeAttribute so it gets run before any tests in that assembly.

All the normal tests run normally, and if they in some way cause the system to interact with the test spy then the interaction happens totally silently, for example maybe the test spy logs the interaction by adding an item to an internal collection.

So what about the 1% of the tests that really want to test against the test spy (the tests that might otherwise have used a mock). Well in the test fixture initialization we reset the test spy then at the end of each test we ask the test spy what calls it received and verify that they were what we expected.

This works a treat, really simple solution that makes the tests very easy to write.

NOTE - When to call services from the domain
The comment from Andreas made me realize that I didn't say when I think a domain class should talk to a service.

Normally I avoid these sorts of dependencies in order to keep the domain code clean, simple and easily testable. However for cross cutting concerns like logging/dirty tracking an AOP based approach (see my PostSharp posts) where we introduce the code that calls the service is very clean.

In particular this works because for those cases we can have the domain class contact the (infrastructure) Service but we don't care about any return values, hence the applicability of a Test Spy.

Share This - Digg It Save to del.icio.us Stumble It! Kick It DZone

Wednesday, January 23, 2008

Styles Of TDD for your Domain Model

Having read a lot of mockobjects.com I'm beginning to understand need-driven development and the effect on design. This has made me want to re-read some old articles:

These are all good posts but I'm coming to the conclusion that there just isn't that much real content out there about how to use interaction testing as a design and testing activity for domain entities/value objects. Seems like a lot of people don't do it and so far the ones that do haven't written that much about it.

The content I have found has semed to be producing designs that I wouldn't be that interested in and although the idea of extracting role interfaces from high level domain entities interests me I can't find any real evidence that people are doing it meaningfully. I'm also not sure that doing it is going to improve the design that much.

Anyway I think for now I'm better focussing my design efforts on traditional DDD activities, whilst keeping an eye on what the BDD/mockobjects.com guys produce.

Share This - Digg It Save to del.icio.us Stumble It! Kick It DZone

Tuesday, January 22, 2008

Interesting Posts About Tests Influencing Design

Oddly I started reading a post by Jay Flowers, which led me to re-read a linked post at mockobjects.com which in turn led me to the most relevant post of all about testing domain classes. I'm glad I followed the links because there is some good info in these posts.

Shifting The Focus
Jay Flowers is thinking about testing and design at the minute too and has just posted about how it affects design in a post called Shifting The Focus.

Test Smell : Everything Is Mocked
I read the post Test Smell: Everything is mocked some time ago but never blogged about it but I do definitely think its worth reading.

I fully agree with the post, directly mocking external API's is often going to be a mistake and your better to use TDD to evolve a wrapper. I also think mocking value objects is a bit of a no-no.

Note there is a TDD thread related to mocking value objects.

Testing Domain Classes
J. B. Rainsberger has a post called A sign you're mocking too much which I whole heartedly agree with.

One of the main points in the post is summed up in this line "Never mock values, sometimes mock entities, but mock services freely". I agree with this and that's basically the way I test domain classes too:

  1. Value Objects - No reason to mock, they should be simple to construct.
  2. Entities - I tend to create real instances using Object Mother or Test Data Builder objects. Occassionally I'll stub an entity but very rarely will I mock it.
  3. Services - Mock away, including mocking repositories.

This also ties in nicely with Eric Evans' opinions from the Testing The Domain thread on the DDD forum. It also indicates that some DDD practitioners (including myself) are using TDD to influence design in ways other than those that we would get to if we purely used interaction testing.

I think I'm going to start to focus on looking at our domain tests and object mothers to see what they are telling us about problems with our current designs.

Share This - Digg It Save to del.icio.us Stumble It! Kick It DZone

Monday, January 21, 2008

Roy Osherove - The Case For TypeMock

Roy Osherove has another post on the case for TypeMock.

For me the big one is that design for testability has its limits. Breaking encapsulation, interfaces over all your classes, injecting everything, virtual members everywhere. Those things can be good and they can also lead to klunky designs particular in domain/business code).

That doesn't mean that design for testability isn't good. However when I want to mock something without changing its design, because I'm quite happy with its current design, I turn to TypeMock.

Share This - Digg It Save to del.icio.us Stumble It! Kick It DZone

Wednesday, January 16, 2008

Interaction Testing of Service Collaborations

I decided to try to follow true interaction testing guidelines and use it as a design technique, specifically a technique to elicit roles and ISP compliant interfaces for DDD SERVICES.

At the minute I'm looking at how we can track changes to our domain objects so that we can report them (where appropriate) to external systems. We've decided to try using PostSharp, applying attributes to classes/members and the attributes will then cause the appropriate code to be inserted.

Interaction Test Driving The Initial Design
In my experience starting a large piece of work like this can be tricky. I've done some prototypes on using PostSharp and we basically know how we want the design to proceed.

To get me started though I need to write a high level test of this form, I decided to make it an interaction test and use TypeMock:

    [TestMethod]
    public void CanTrackCustomerActivation()
    {
        Customer customer = CustomerObjectMother.CreateProspect();
 
        DomainChangeMessage expectedMessage = new DomainChangeMessage(customer,
        "CustomerActivated");
 
        #region Mocking
 
        Mock serviceMock = MockManager.MockObject(typeof(IChangeTrackingService));
        serviceMock.ExpectCall("EventOccurred").Args(expectedMessage);
 
        IChangeTrackingService service = (IChangeTrackingService)serviceMock.MockedInstance;
 
        Mock serviceLocatorMock = MockManager.Mock(typeof(ServiceLocator), Constructor.Mocked);
        serviceLocatorMock.ExpectAndReturn("GetChangeTrackingService", service);
 
        #endregion
 
        customer.Activate();
 
        MockManager.Verify();
    } 

This test shows the following:
  1. We'll have a service of type IChangeTrackingService and we expect its EventOccurred method to be called.

  2. We expect the service to be retrieved from the existing ServiceLocator class (we considered using IoC but for now this will do, YAGNI).

Most importantly the test has helped us explore and confirm the design (see below) and although I'm not always made on interaction testing I think this one was useful.

To get the test pass all I need to do is put this sort of code into the Customer.ActivateMethod:

ServiceLocator.GetDomainChangeTrackingService().DomainEventOccurred(new DomainChangeMessage(this, "CustomerActivated"));

I'd refactor this code, but its a strarting point.

I need to make DomainChangeMessage a VALUE OBJECT to get this to pass (override Equals particularly). It was also nice that testing the changes I needed to make to DomainChangeMessage to turn it into a VALUE OBJECT (particularly overriding equals) was easy because I've written a helper class to deal with this in the past.

Importance Of The Test
In this case I'm happy that the test I created is very readable and shows clearly what the high level collaborations are.

The effect of this test on the design is subtle. I'd have designed this the same way regardless, the seperated interface (IChangeTrackingService) approach is one that works quite well and it's clear that DomainChangeMessage should be a VALUE OBJECT. However proving that this design is sound using an interaction test is valuable.

The next step is to write a test that actually checks that with a real instance of the SERVICE you get the correct behavior, which in this case might be just to save the DomainChangeMessage and make it available for use in the verification part of the test.

Oh but....
This is a bit of a cop out, every test that shows interaction testing uses it to get the role for a service style class.

What I'm really interested in is seeing how people use the same approach for domain ENTITIES, I'm not so sure that the ISP style interfaces you'd extract from them in order to get these tests to pass are so useful.

I'm prepared to be convinced though and the mock objects do seem to indicate that they think this approach can work for domain entities so I'm interested to see what they come up with.

Share This - Digg It Save to del.icio.us Stumble It! Kick It DZone

Sunday, January 13, 2008

DDD with AOP and DI Presentation

A new DDD thread links to a talk about using AOP and DI to support DDD. The talk itself is very interesting, not sure I agree with all of it but it is good.

Share This - Digg It Save to del.icio.us Stumble It! Kick It DZone

Sunday, December 30, 2007

BDD/TDD - What Drives The Domain Design

In view of the discussion of BDD[1][2] I've started to look at the way we specify/test our domain model. A great promise of BDD is that your tests will drive the design of your domain model and that the tests themselves will help explain the design of the domain.

My efforts to get to the essence of BDD have left me very confused and in an effort to better understand BDD I actually went to the Test Driven Development Yahoo group. I've been subscribed to it for a while but I'd never realized how good it is. Well informed discussion and heavyweights like Ron Jeffries/Kent Beck wading in. Great stuff and seems to me to have a similiar feel to the DDD group.

Anyway I came across one particularly useful thread. It doesn't really cover BDD directly but it does cover state/interaction testing and how they influence the way you design. In particular it contains a couple of great posts including this one which tries to get the to real essence of interaction and state testing and the way they affect your design.

I was already well aware of the difference between state and interaction testing but this single post summed things up very nicely and reminded me of a few things.

Personally I refactor, including to patterns, a lot. As I do I find my code changes massively which affects the way I test. Let me give you a representative example...

Example - State Testing/Refactoring Driving The Design
We need to allow people to debit Accounts in our system, a test to kick off this work might be

Account sourceAccount = ...;
Account targetAccount = ...;
Money amountToDebit = ...;

Money originalValueTargetAccount = targetAccount.Balance();
Money originalValueSourceAccount = sourceAccount.Balance();

FundsTransferService.Transfer(sourceAccount, targetAccount, amountToDebit); // code under test

Assert.AreEqual(originalValue - amountToDebit, account.Balance);

I'm not saying this the exact test I'd start with but its representative of the sorts of tests I'd be writing. This is a pure state test and in Ron Jeffries terminology is testing functionality not sequence.

As I go I'd be writing more and more tests and more and more code. As I went I'd refactor and after a while the method may be delegating to Specifications, Rules, Method Objects, Strategies, Entities, ValueObjects, Factories and other classes to do its work.

Some of the new classes will merely exist to ensure the code reads well (pure fabrications in Larman terminology).

As I extracted these pure fabrications I probably wouldn't change the tests, leaving them at the level that they started at (FundTransferService). I could change the tests to be tests specific to the new rule though. I'd just extract the code, ensure the tests passed, refactor the tests, ensure they passed...but then pure fabrications are very much open to redesign at any time so I'm not sure it makes so much sense to write tests for them specifically (questionable?).

Anyway what this means that I'm doing top down development (starting at public interface to the domain) but I'm not using stubbing or interaction testing, instead I use state testing and evolve the code and refactor a lot until I'm pretty happy.

Alternative - Interaction Tests Driving The Design

So the question is what is driving me to change the design, if I was doing proper interaction testing then I would be defining the interactions and then writing the code to fulfill it.

I could probably do this for the high level interactions, for example between entities. I'm not sure I want to include that information in every test but I could use it as a design technique and encode it in a few tests. This is quite high level interactions so I avoid the risk of overspecified software.

Ultimately I would still need some state tests (see this thread for a good discussion of the reason you still need state tests) but I'd be using interaction testing to drive my design.

However as I say I find a domain model is filled with all sorts of little domain classes that only exist because we chose to refactor the code to make it read better, these classes are not necessarily part of the ubiquitous language and are purely an imeplementation detail (they are pure fabrications).

Making interaction testing work for these pure fabrications seems to me to be a bit of a bad idea, these classes exist because of refactoring and I cannot plan for the interactions with them upfront.

Maybe if I stick to only using interaciton testing for the high level interactions, rather than interactions with pure fabrications, I'll get the benefits of interaction testing without the costs. I think thats what I'll try next.

Share This - Digg It Save to del.icio.us Stumble It! Kick It DZone

Wednesday, November 28, 2007

AOP - Alternatives To PostSharp

Whilst looking at PostSharp I found quite a few useful links and also managed to look at a few alternatives.

Aspect# seemed interesting but it only does virtual members (or interfaces I presume) and its certainly not transparent to the user of the classes as you have to go through an AspectEngine. Anyway no matter how useful it could have been it looks like Aspect# is a dead end and is on the way out.

Other than Aspect# there are a few other choices, Spring.NET has an AOP solution and Eric Bodden has a list of .NET AOP solutions and I'll definitely take a look at some of them, AspectDNG in particular sounds good.

I'll be interested to see if I can find any solution thats as simple as PostSharp Laos or that has such a nice way of supporting compile-time weaving.

Links - PostSharp

  1. Using AOP for validation
  2. PostSharp AOP reference
  3. AOP with PostSharp Part A
  4. AOP with PostSharp Part B
  5. Bitter Coder
  6. DotNetKicks - Not much yet...

Links - AOP

  1. Ayende - 7 Approaches To AOP In .NET
  2. Characterization Of Current Approaches
  3. Spring.NET
  4. Eric Boddens List Of Current Approaches
  5. Wikipedia

Share This - Digg It Save to del.icio.us Stumble It! Kick It DZone