|
|
Archive for the ‘DDD’ Category
Monday, June 29th, 2009

My previous post on Domain Events left some questions about how aggregate roots should be created unanswered. It would actually be more accurate to say how aggregate roots should *not* be created. It turns out that this is one of the less intuitive parts of domain-driven design and has been the source of many arguments on the matter. Let’s start with the wrong way:
1: using (ISession s = sf.OpenSession())
2: using (ITransaction tx = s.BeginTransaction())
3: {
4: Customer c = new Customer();
5: c.Name = "udi dahan";
6:
7: s.Save(c);
8: tx.Commit();
9: }
I understand that the code above is representative of how much code is written when using an object-relational mapper. Many would consider this code to follow DDD principles – that Customer is an aggregate root. Unfortunately – that is not the case. The code above is missing the real aggregate root.
There’s also the inevitable question of validation – if the customer object isn’t willing to accept a name with a space in it, should we throw an exception? That would prevent an invalid entity from being saved, which is good. On the other hand, exceptions should be reserved for truly exceptional occurrences. But if we don’t use exceptions, using Domain Events instead, how do we prevent the invalid entity from being saved?
All of these issues are handled auto-magically once we have a true aggregate root.
Always Get An Entity
Let’s start with the technical guidance – always get an entity. At least one. Also, don’t add any objects to the session or unit of work explicitly – rather, have some other already persistent domain entity create the new entity and add it to a collection property.
Looking at the code above, we see that we’re not following the technical guidance.
But the question is, which entity could we possibly get from the database in this case? All we’re doing is adding a customer.
And that’s exactly where the technical guidance leads us to the business analysis that was missing in this scenario…
Business Analysis
Customers don’t just appear out of thin air.
Blindingly obvious – isn’t it.
So why would we technically model our system as if they did? My guess is that we never really thought about it – it wasn’t our job. So here’s the breaking news – if we want to successfully apply DDD we do need to think about it, it is our job.
Going back to the critical business question:
Where do customers come from?
In the real world, they stroll into the store. In our overused e-commerce example, they navigate to our website. New customers that haven’t used our site before don’t have any cookies or anything we can identify them with. They navigate around, browsing, maybe buying something in the end, maybe not.
Yet, the browsing process is interesting in its own right:
- Which products did they look at?
- Did they use the search feature?
- How long did they spend on each page?
- Did they scroll down to see the reviews?
If and when they do finally buy something, all that history is important and we’d like to maintain a connection to it.
Actually, even before they buy something, what they put in their cart is the interesting piece. The transition from cart to checkout is another interesting piece. Do they actually complete the checkout process, or do they abandon it midway through?
Add to that when we ask/force them to create a user/login in our system.
Are they actually a customer if they haven’t bought anything?
We’re beginning to get an inkling that almost every activity that results in the creation of an entity or storing of additional information can be traced to a transition from a previous business state.
In any transition, the previous state is the aggregate root.
In the beginning…
Let’s start at the very beginning then – someone came to our site. Either they navigated here from some other web page, they clicked on an email link someone sent them, or they typed in our URL. This can be designed as follows:
1: using (ISession s = sf.OpenSession())
2: using (ITransaction tx = s.BeginTransaction())
3: {
4: var referrer = s.Get<Referrer>(msg.URL);
5: referrer.BroughtVisitorWithIp(msg.IpAddress);
6:
7: tx.Commit();
8: }
9:
And our referrer code could look something like this:
1: public void BroughtVisitorWithIp(string ipAddress)
2: {
3: var visitor = new Visitor(ipAddress);
4: this.NewVisitors.Add(visitor);
5: }
6:
This follows the technical guidance we saw at the beginning.
It also allows us to track which referrer is bringing us which visitors, through tracking those visitors as they become shoppers (by putting stuff in their cart), finally seeing which become customers.
We can solve the situation of not having a referrer by implementing the null object pattern which is well supported by all the standard object-relational mappers these days.
How it works internally
When we call a method on a persistent entity retrieved by the object-relational mapper, and the entity modifies its state like when it adds a new entity to one of its collection properties, when the transaction commits, here’s what happens:
The mapper sees that the persistent entity is dirty, specifically, that its collection property was modified, and notices that there is an object in there that isn’t persistent. At that point, the mapper knows to persist the new entity without us ever having to explicitly tell it to do so. This is sometimes known as “persistence by reachability”.
Where validation happens
Let’s consider the relatively trivial rule that says that a user name can’t contain a space.
Also, keep in mind that a registered user is the result of a transition from a visitor.
Here’s *one* way of doing that:
1: public class Visitor
2: {
3: public void Register(string username, string password)
4: {
5: if (username.Contains(" "))
6: {
7: DomainEvents.Raise<UsernameCantContainSpace>();
8: return;
9: }
10:
11: var user = new User(username, password);
12: this.RegisteredUser = u;
13: }
14: }
15:
This actually isn’t representative of most of the rules that will be found in the domain model, but it illustrates a way of preventing an entity from being created without our service layer needing to know anything. All the service layer does is get the visitor object and call the Register method.
Validation of string lengths, data ranges, etc is not domain logic and is best handled elsewhere (and a topic for a different post). The same goes for uniqueness.
Summary
The most important thing to keep in mind is that if your service layer is newing up some entity and saving it – that entity isn’t an aggregate root *in that use case*. As we saw above, in the original creation of the Visitor entity by the Referrer, the visitor class wasn’t the aggregate root. Yet, in the user registration use case, the Visitor entity was the aggregate root.
Aggregate roots aren’t a structural property of the domain model.
And in any case, don’t go saving entities in your service layer – let the domain model manage its own state. The domain model doesn’t need any references to repositories, services, units of work, or anything else to manage its state.
If you do all this, you’ll also be able to harness the technique of fetching strategies to get the best performance out of your domain model by representing your use cases as interfaces on the domain model like IRegisterUsers (implemented by Visitor) and IBringVisitors (implemented by Referrer).
And spending some time on business analysis doesn’t hurt either – unless customers really do fall out of the sky in your world
Posted in DDD, NHibernate, OO, Validation | 72 Comments »
Sunday, June 14th, 2009

I’ve been hearing from people that have had a great deal of success using the Domain Event pattern and the infrastructure I previously provided for it in Domain Events – Take 2. I’m happy to say that I’ve got an improvement that I think you’ll like. The main change is that now we’ll be taking an approach that is reminiscent to how events are published in NServiceBus.
Background
Before diving right into the code, I wanted to take a minute to recall how we got here.
It started by looking for how to create fully encapsulated domain models.
The main assertion being that you do *not* need to inject anything into your domain entities.
Not services. Not repositories. Nothing.
Just pure domain model goodness.
Make Roles Explicit
I’m going to take the advice I so often give. A domain event is a role, and thus should be represented explicitly:
1: public interface IDomainEvent {}
If this reminds you of the IMessage marker interface in nServiceBus, you’re beginning to see where this is going…
How to define domain events
A domain event is just a simple POCO that represents an interesting occurence in the domain. For example:
1: public class CustomerBecamePreferred : IDomainEvent
2: {
3: public Customer Customer { get; set; }
4: }
For those of you concerned about the number of events you may have, and therefore are thinking about bunching up these events by namespaces or things like that, slow down. The number of domain events and their cohesion is directly related to that of the domain model.
If you feel the need to split your domain events up, there’s a good chance that you should be looking at splitting your domain model too. This is the bottom-up way of identifying bounded contexts.
How to raise domain events
In your domain entities, when a significant state change happens you’ll want to raise your domain events like this:
1: public class Customer
2: {
3: public void DoSomething()
4: {
5: DomainEvents.Raise(new CustomerBecamePreferred() { Customer = this });
6: }
7: }
We’ll look at the DomainEvents class in just a second, but I’m guessing that some of you are wondering “how did that entity get a reference to that?” The answer is that DomainEvents is a static class. “OMG, static?! But doesn’t that hurt testability?!” No, it doesn’t. Here, look:
Unit testing with domain events
One of the things we’d like to check when unit testing our domain entities is that the appropriate events are raised along with the corresponding state changes. Here’s an example:
1: public void DoSomethingShouldMakeCustomerPreferred()
2: {
3: var c = new Customer();
4: Customer preferred = null;
5:
6: DomainEvents.Register<CustomerBecamePreferred>(
7: p => preferred = p.Customer
8: );
9:
10: c.DoSomething();
11: Assert(preferred == c && c.IsPreferred);
12: }
As you can see, the static DomainEvents class is used in unit tests as well. Also notice that you don’t need to mock anything – pure testable bliss.
Who handles domain events
First of all, consider that when some service layer object calls the DoSomething method of the Customer class, it doesn’t necessarily know which, if any, domain events will be raised. All it wants to do is its regular schtick:
1: public void Handle(DoSomethingMessage msg)
2: {
3: using (ISession session = SessionFactory.OpenSession())
4: using (ITransaction tx = session.BeginTransaction())
5: {
6: var c = session.Get<Customer>(msg.CustomerId);
7: c.DoSomething();
8:
9: tx.Commit();
10: }
11: }
The above code complies with the Single Responsibility Principle, so the business requirement which states that when a customer becomes preferred, they should be sent an email belongs somewhere else.
Notice that the key word in the requirement – “when”.
Any time you see that word in relation to your domain, consider modeling it as a domain event.
So, here’s the handling code:
1: public class CustomerBecamePreferredHandler : Handles<CustomerBecamePreferred>
2: {
3: public void Handle(CustomerBecamePreferred args)
4: {
5: // send email to args.Customer
6: }
7: }
This code will run no matter which service layer object we came in through.
Here’s the interface it implements:
1: public interface Handles<T> where T : IDomainEvent
2: {
3: void Handle(T args);
4: }
Fairly simple.
Please be aware that the above code will be run on the same thread within the same transaction as the regular domain work so you should avoid performing any blocking activities, like using SMTP or web services. Instead, prefer using one-way messaging to communicate to something else which does those blocking activities.
Also, you can have multiple classes handling the same domain event. If you need to send email *and* call the CRM system *and* do something else, etc, you don’t need to change any code – just write a new handler. This keeps your system quite a bit more stable than if you had to mess with the original handler or, heaven forbid, service layer code.
Where domain event handlers go
These handler classes do not belong in the domain model.
Nor do they belong in the service layer.
Well, that’s not entirely accurate – you see, there’s no *the* service layer. There is the part that accepts messages from clients and calls methods on the domain model. And there is another, independent part that handles events from the domain. Both of these will probably make use of a message bus, but that implementation detail shouldn’t deter you from keeping each in their own package.
The infrastructure
I know you’ve been patient, reading through all my architectural blah-blah, so here it is:
1: public static class DomainEvents
2: {
3: [ThreadStatic] //so that each thread has its own callbacks
4: private static List<Delegate> actions;
5:
6: public static IContainer Container { get; set; } //as before
7:
8: //Registers a callback for the given domain event
9: public static void Register<T>(Action<T> callback) where T : IDomainEvent
10: {
11: if (actions == null)
12: actions = new List<Delegate>();
13:
14: actions.Add(callback);
15: }
16:
17: //Clears callbacks passed to Register on the current thread
18: public static void ClearCallbacks ()
19: {
20: actions = null;
21: }
22:
23: //Raises the given domain event
24: public static void Raise<T>(T args) where T : IDomainEvent
25: {
26: if (Container != null)
27: foreach(var handler in Container.ResolveAll<Handles<T>>())
28: handler.Handle(args);
29:
30: if (actions != null)
31: foreach (var action in actions)
32: if (action is Action<T>)
33: ((Action<T>)action)(args);
34: }
35: }
Notice that while this class *can* use a container, the container isn’t needed for unit tests which use the Register method.
When used server side, please make sure that you add a call to ClearCallbacks in your infrastructure’s end of message processing section. In nServiceBus this is done with a message module like the one below:
1: public class DomainEventsCleaner : IMessageModule
2: {
3: public void HandleBeginMessage() { }
4:
5: public void HandleEndMessage()
6: {
7: DomainEvents.ClearCallbacks();
8: }
9: }
The main reason for this cleanup is that someone just might want to use the Register API in their original service layer code rather than writing a separate domain event handler.
Summary
Like all good things in life, 3rd time’s the charm.
It took a couple of iterations, and the API did change quite a bit, but the overarching theme has remained the same – keep the domain model focused on domain concerns. While some might say that there’s only a slight technical difference between calling a service (IEmailService) and using an event to dispatch it elsewhere, I beg to differ.
These domain events are a part of the ubiquitous language and should be represented explicitly.
CustomerBecamePreferred is nothing at all like IEmailService.
In working with your domain experts or just going through a requirements document, pay less attention to the nouns and verbs that Object-Oriented Analysis & Design call attention to, and keep an eye out for the word “when”. It’s a critically important word that enables us to model important occurrences and state changes.
What do you think? Are you already using this approach? Have you already tried it and found it broken in some way? Do you have any suggestions on how to improve it?
Let me know – leave a comment below.
Posted in Architecture, DDD, Data Access, Development, Testing | 155 Comments »
Monday, January 26th, 2009
I finally got around to listening to the alt.net podcast on domain driven design and heard Rob Conery telling about his experiences with DDD. I’ve met a fair amount of developers that went through a similar process and thought that I could help fix some of the common misconceptions that pop up when developers start down the DDD path.

Factory methods on repositories
In the podcast, Rob describes an ecommerce application with orders, customers, products – all the stuff you’ve come to expect. In his pre-DDD design, the order class had multiple constructors representing different rules. Feeling the pain in testing and maintainability, Rob looked to use DDD principles. What he did to get rid of these constructors was to make use of the repository by creating methods for the various cases, like OrderRepository.CreateOrderForGovernmentCustomer(/*data*/); .
While this is better than the multiple constructors, it still has a way to go. Analyzing what’s going on here we understand that the way the order is created is dependent upon who the user is. The rules dictating terms of payment are probably different for government customers. Not only that but we know that the order created needs to be connected to that user.
Aggregate Roots & Polymorphism
For all these reasons, it looks like user, or customer, is our aggregate root. Thus, rather than our service layer calling the above method on the repository, we first get the user object by id, then create the order like so:
IUser u = session.Get<IUser>(IdOfUserLoggedIn); u.CreateOrder(/* data */);
This way, our service layer doesn’t need to perform all sorts of business logic (if the user is a gov’t user, do this, a corporate customer, do that, etc). All of that gets encapsulated by the domain. By leveraging some polymorphism, the session will return an instance of the correct class when we ask it for a user by id. Thus, logic relating to how gov’t users create orders is encapsulated in the GovernmentUser class.
I’ve found that this pattern of having polymorphic aggregate roots is very useful and broadly applicable.
Bounded Contexts
Further into the podcast, Rob talks about how separating his system into 2 bounded contexts simplified the code greatly. The understanding that accepting an order and fulfilling an order require different logic, different data, and thus, different domain model objects is DDD at its finest.
However, when talking about the total cost of the order, it wasn’t clear what was responsible for that. From a pure programming perspective, we might think that Total was simply a property on Order or, at most, a GetTotal() method. Yet by looking at what is involved in calculating the total of an order, a different picture emerges:
The total cost of an order obviously includes all relevant taxes. We need to take into account state and federal taxes, tax-free items at each level, etc. There’s a fair amount of logic here. Once we start to take into account promotions like “buy one, get one free”, things get even more involved. There are also cases where refunds are applied within the same order that impact the total and tax (no tax on refunds). Finally, when we include shipping charges, tax on shipping, and other rules between all of the above, it’s clear that if we put all of this in a single method, we’ve got ourselves a big bloated sack of … well, you get the picture.
Separating all of this logic into different bounded contexts makes sense.
That is, until you think about how you’re going to take these and stitch out of them a single result shown to the user. This is the advanced side of DDD and ties into SOA, so I’ll leave it for a different post.
In Closing
Working with DDD provides a great deal of value by tying our code much more closely to business concepts and encapsulating business rules in the domain model.
Starting down the DDD path is intuitive and the code that results (like u.CreateOrder) is very understandable. Yet, as more DDD principles like Bounded Contexts are put to use, developers often find themselves in unfamiliar, less-intuitive waters. This is to be expected.
Some developers (and vendors) look at DDD as nothing more than the domain model and repository patterns. The truth is that they’re just the beginning.
I hope that this post has given those of you just starting down the DDD path some feeling for how deep the rabbit hole goes, and I assure you that there are patterns in place to answer all your questions. While those beginning DDD often say that it gives names to things they’ve always been doing, or always wanted to do, I can assure you that the further down you go, that is less and less the case.
Be ready to have some basic architectural assumptions shaken
Posted in DDD, OO | 17 Comments »
Saturday, January 24th, 2009
The ability to map entity relationships is broadly supported by many O/RM tools. For some reason, though, many developers run into issues when trying to map a many-to-many relationship between entities. Although much has already been written about the technological aspects of it, I thought I’d take more of an architectural / DDD perspective on it here.
Value Objects Don’t Count
While the canonical example presented is Customer -> Address, and has a good treatment here for nHibernate, it isn’t architecturally representative.
Addresses are value objects. What this means is that if we have to instance of the Address class, and they both have the same business data, they are semantically equivalent. Customers, on the other had, are not value objects – they’re entities. If we have two customers with the same business data (both of them called Bob Smith), that does not mean they are semantically equivalent – they are not the same person.
All Entities
Therefore, for our purposes here we’ll use something different. Say we have an entity called Job which is something that a company wants to hire for. It has a title, description, skill level, and a bunch of other data. Say we also have another entity called Job Board which is where the company posts jobs so that applicants can see them, like Monster.com. A job board has a name, description, web site, referral fee, and a bunch of other data.
A job can be posted to multiple job boards. And a job board can have multiple jobs posted. A regular many to many relationship. At this point, we’re not even going to complicate the association.
This is simply represented in the DB with an association table containing two columns for each of the entity tables’ ids.
In the domain model, developers can also represent this with the Job class containing a list of JobBoard instances, and the JobBoard class containing a list of jobs.
It’s intuitive. Simple. Easy to implement. And wrong.
In order to make intelligent DDD choices, we’re going to first take what may seem to be a tangential course, but I assure you that your aggregate roots depend on it.
Moving forward with our example
Let’s say the user picks a job, and then ticks off the job boards where they want the job posted, and clicks submit.
For simplicity’s sake, at this point, let’s ignore the communication with the actual job sites, assuming that if we can get the association into the DB, magic will happen later causing the job to appear on all the sites.
Our well-intentioned developer takes the job ID, and all the job board IDs, opens a transaction, gets the job object, gets the job board objects, adds all the job board objects to the job, and commits, as follows:
1: public void PostJobToBoards(Guid jobId, params Guid[] boardIds)
2: {
3: using (ISession s = this.SessionFactory.OpenSession())
4: using (ITransaction tx = s.BeginTransaction())
5: {
6: var job = s.Get<Job>(jobId);
7: var boards = new List<JobBoard>();
8:
9: foreach(Guid id in boardIds)
10: boards.Add(s.Get<JobBoard>(id));
11:
12: job.PostTo(boards);
13:
14: tx.Commit();
15: }
16: }
In this code, Job is our aggregate root. You can see that is the case since Job is the entry point that the service layer code uses to interact with the domain model. Soon we’ll see why this is wrong.
** Notice that in this service layer code, our well-intentioned developer is following the rule that while you can get as many objects as you like, you are only allowed one method call on one domain object. The code called in line 12 is what you’d pretty much expect:
1: public void PostTo(IList<JobBoard> boards)
2: {
3: foreach(JobBoard jb in boards)
4: {
5: this.JobBoards.Add(jb);
6: jb.Jobs.Add(this);
7: }
8: }
Only that as we were committing, someone deleted one of the job boards just then. Or that someone updated the job board causing a concurrency conflict. Or anything that would cause one single association to not be created.
That would cause the whole transaction to fail and all changes to roll back.
Rightly so, thinks our well-intentioned developer.
But users don’t think like well-intentioned developers.
Partial Failures
If I were to go to the grocery store with the list my wife gave me, finding that they’re out of hazelnuts (the last item on the list), would NOT buy all the other groceries and go home empty handed, what do you think would happen?
Right. That’s how users look at us developers. Before running off and writing a bunch of code, we need to understand the business semantics of users actions, including asking about partial failures.
The list isn’t a unit of work that needs to succeed or rollback atomically. It’s actually many units of work. I mean, I wouldn’t want my wife to send me to the store 10 times to buy 10 items, so the list is really just a kind of user shortcut. Therefore, in the job board scenario, each job to job board connection is its own transaction.
This is more common than you might think.
Once you go looking for cases where the domain is forgiving of partial failures, you may start seeing more and more of them.
Aggregate Roots
In the original transaction where we tried to connect many job boards to a single job, we saw that the single job is the aggregate root. However, once we have multiple transactions, each connecting one job and one job board, the job board is just as likely an aggregate root as the job.
We can do jobBoard.Post(job); or job.PostTo(jobBoard);
But we need just a bit more analysis to come to the right decision.
While we could just leave the bi-directional/circular dependency between them, it would be preferable if we could make it uni-directional instead. To do that, we need to understand their relationship:
If there was no such thing as “job”, would there be meaning to “job board” ? Probably not.
If there was no such thing as “job board”, would there be meaning to “job” ? Probably. Yes. Our company can handle the hiring process of a job regardless of whether the candidate came in through Monster.com or not.
From this we understand that the uni-directional relationship can be modelled as one-to-many from job board to job. The Job class would no longer have a collection of Job Board objects. In fact, it could even be in an assembly separate from Job Board and not reference Job Board in any way. Job Board, on the other hand, would still have a collection of Job objects.
Going back to the code above we see that the right choice is jobBoard.Post(job);
Job Board is the aggregate root in this case. Also, the many-to-many mapping has now dissolved, leaving behind a single one-to-many mapping.
Let that sink in a second.
But Wait…
While the GUI showing which jobs are posted on a given job board are well served by the above decision (simply traversing the object graph from Job Board to its collection of Jobs), that’s not the whole story. Another GUI needs to show administrative users which Job Boards a given Job has been posted to. Since we no longer have the domain-level connection, we can’t traverse myJob.JobBoards.
Our only option is to perform a query. That’s not so bad, but not as pretty as object traversal.
The real benefit is in chopping apart the Gordian M-to-N mapping knot and getting a cleaner, more well factored domain model.
That gives us much greater leverage for bigger, system-level decomposition.
We’re now all set to move up to a pub/sub solution between these aggregate roots, effectively upgrading them to Bounded Contexts. From there, we can move to full-blown internet-scale caching with REST for extra scalability on showing a job board with all its jobs.
In Closing
We often look at many-to-many relationships just like any other relationship. And from a purely technical perspective, we’re not wrong. However, the business reality around these relationships is often very different – forgiving of partial failures, to the point of actually requiring them.
Since the business folks who provide us with requirements rarely think of failure scenarios, they don’t specify that “between these two entities here, I don’t want transactional atomicity” (rolling our technical eyes – the idiots [sarcasm, just to make sure you don't misread me]).
Yet, if we were to spell out what the system will do under failure conditions when transactionally atomic, those same business folks will be rolling our eyes back to us.
What I’ve found surprises some DDD practitioners is how critical this issue really is to arriving at the correct aggregate roots and bounded contexts.
It’s also simple, and practical, so you won’t be offending the YAGNI police.
Related Content
From CRUD to Domain-Driven Fluency
[Podcast] Domain Models, SOA, and The Single Version of the Truth
Posted in Architecture, DDD, Data Access, Databases, NHibernate | 26 Comments »
Monday, August 25th, 2008
Update: The next post in this series is now online here.
My previous post on how to create fully encapsulated domain models introduced the concept of events as a core pattern of communication from the domain back to the service layer. In that post, I put up enough code to get the idea across but didn’t address issues like memory leaks and multi-threading. This post will show the solution to those two critical points.
I’ve snipped out one of the events in the previous example for brevity.
Previous API
The previous API looked like this:
1: public static class DomainEvents
2: {
3: public static event EventHandler GameReportedLost;
4: public static void RaiseGameReportedLostEvent()
5: {
6: if (GameReportedLost != null)
7: GameReportedLost(null, null);
8: }
9:
10: public static event EventHandler CartIsFull;
11: public static void RaiseCartIsFull()
12: {
13: if (CartIsFull != null)
14: CartIsFull(null, null);
15: }
16: }
One thing that we want to keep in the solution is that all the code to define events, their names, and the parameters they bring will be in one place – in this case, the DomainEvents class. One thing that we’d like to fix is the amount of code needed to define an event.
Previous Service Layer
Here’s what our previous service layer code looked like:
1: public class AddGameToCartMessageHandler :
2: BaseMessageHandler<AddGameToCartMessage>
3: {
4: public override void Handle(AddGameToCartMessage m)
5: {
6: using (ISession session = SessionFactory.OpenSession())
7: using (ITransaction tx = session.BeginTransaction())
8: {
9: ICart cart = session.Get<ICart>(m.CartId);
10: IGame g = session.Get<IGame>(m.GameId);
11:
12: Domain.DomainEvents.GameReportedLost +=
13: gameReportedLost;
14: Domain.DomainEvents.CartIsFull +=
15: cartIsFull;
16:
17: cart.Add(g);
18:
19: Domain.DomainEvents.GameReportedLost -=
20: gameReportedLost;
21: Domain.DomainEvents.CartIsFull -=
22: cartIsFull;
23:
24: tx.Commit();
25: }
26: }
27:
28: private EventHandler gameReportedLost = delegate {
29: Bus.Return((int)ErrorCodes.GameReportedLost);
30: };
31:
32: private EventHandler cartIsFull = delegate {
33: Bus.Return((int)ErrorCodes.CartIsFull);
34: };
35: }
36: }
Another thing that should be improved is the amount of code needed in the service layer.
Raising an event, though, should still be fairly simple – one line of code similar to DomainEvents.RaiseGameReportedLost().
New API
Here’s what the new API looks like:
1: public static class DomainEvents
2: {
3: public static readonly DomainEvent<IGame> GameReportedLost =
4: new DomainEvent<IGame>;
5:
6: public static readonly DomainEvent<ICart> CartIsFull=
7: new DomainEvent<ICart>;
8: }
It looks like we’ve managed to bring down the complexity of defining an event.
Raising an event is slightly different, but still only one line of code (”this” refers to the Cart class that is calling this API): DomainEvents.CartIsFull.Raise(this);
New Service Layer
The advantage of having a disposable domain event allows us to use the “using” construct for cleanup.
1: public class AddGameToCartMessageHandler :
2: BaseMessageHandler<AddGameToCartMessage>
3: {
4: public override void Handle(AddGameToCartMessage m)
5: {
6: using (ISession session = SessionFactory.OpenSession())
7: using (ITransaction tx = session.BeginTransaction())
8: using (DomainEvents.GameReportedLost.Register(gameReportedLost))
9: using (DomainEvents.CartIsFull.Register(cartIsFull))
10: {
11: ICart cart = session.Get<ICart>(m.CartId);
12: IGame g = session.Get<IGame>(m.GameId);
13:
14: cart.Add(g);
15:
16: tx.Commit();
17: }
18: }
19:
20: private Action<IGame> gameReportedLost = delegate {
21: Bus.Return((int)ErrorCodes.GameReportedLost);
22: };
23:
24: private Action<ICart> cartIsFull = delegate {
25: Bus.Return((int)ErrorCodes.CartIsFull);
26: };
27: }
28: }
I also want to mention that you don’t necessarily have to have the same service layer object handle these events as that which calls the domain objects. In other words, we can have singleton objects handling these events for things like sending emails, notifying external systems, and auditing.
The Infrastructure
The infrastructure that makes all this possible (in a thread-safe way) is quite simple and made up of two parts, the DomainEvent that we saw being used above, and the DomainEventRegistrationRemover which handles the disposing:
1: using System;
2: using System.Collections.Generic;
3:
4: namespace DomainEventInfrastructure
5: {
6: public class DomainEvent<E>
7: {
8: [ThreadStatic]
9: private static List<Action<E>> _actions;
10:
11: protected List<Action<E>> actions
12: {
13: get {
14: if (_actions == null)
15: _actions = new List<Action<E>>();
16:
17: return _actions;
18: }
19: }
20:
21: public IDisposable Register(Action<E> callback)
22: {
23: actions.Add(callback);
24: return new DomainEventRegistrationRemover(delegate
25: {
26: actions.Remove(callback);
27: }
28: );
29: }
30:
31: public void Raise(E args)
32: {
33: foreach (Action<E> action in actions)
34: action.Invoke(args);
35: }
36: }
37: }
38:
Note that the invocation list of the domain event is thread static, meaning that each thread gets its own copy – even though they’re all working with the same instance of the domain event.
Here’s the DomainEventRegistrationRemover – even simpler:
1: using System;
2:
3: namespace DomainEventInfrastructure
4: {
5: public class DomainEventRegistrationRemover : IDisposable
6: {
7: private readonly Action CallOnDispose;
8:
9: public DomainEventRegistrationRemover(Action ToCall)
10: {
11: this.CallOnDispose = ToCall;
12: }
13:
14: public void Dispose()
15: {
16: this.CallOnDispose.DynamicInvoke();
17: }
18: }
19: }
For your convenience, I’ve made these available for download here.
I also want to add that if you haven’t looked at the comments on the original post – there’s some really good stuff there (36 comments so far). Take a look.
Posted in Architecture, DDD, Data Access, Development, Threading | 28 Comments »
Friday, February 29th, 2008
Update: The new and improved solution is now available: Domain Events, Take 2.
Most people getting started with DDD and the Domain Model pattern get stuck on this. For a while I tried answering this on the discussion groups, but here we have a nice example that I can point to next time.
The underlying problem I’ve noticed over the past few years is that developers are still thinking in terms of querying when they need more data. When moving to the Domain Model pattern, you have to “simply” represent the domain concepts in code – in other words, see things you aren’t used to seeing. I’ll highlight that part in the question below so that you can see where I’m going to go with this in my answer:
I have an instance where I believe I need access to a service or repository from my entity to evaluate a business rule but I’m using NHibernate for persistence so I don’t have a real good way to inject services into my entity. Can I get some viewpoints on just passing the services to my entity vs. using a facade?
Let me explain my problem to provide more context to the problem.
The core domain revolves around renting video games. I am working on a new feature to allow customers to trade in old video games. Customers can trade in multiple games at a time so we have a TradeInCart entity that works similar to most shopping carts that everybody is familiar with. However there are several rules that limit the items that can be placed into the TradeInCart. The core rules are:
1. Only 3 games of the same title can be added to the cart. 2. The total number of items in the cart cannot exceed 10. 3. No games can be added to the cart that the customer had previously reported lost with regards to their rental membership. a. If an attempt is made to add a previously reported lost game, then we need to log a BadQueueStatusAddAttempt to the persistence store.
So the first 2 rules are easily handled internally by the cart through an Add operation. Sample cart interface is below.
1: class TradeInCart{
2: Account Account{get;}
3: LineItem Add(Game game);
4: ValidationResult CanAdd(Game game);
5: IList<LineItems> LineItems{get;}
6: }
However the #3 rule is much more complicated and can’t be handled internally by the cart, so I have to depend on external services. Splitting up the validation logic for a cart add operation doesn’t seem very appealing to me at all. So I have the option of passing in a repository to get the previously reported lost games and a service to log bad attempts. This makes my cart interface ugly real quick.
1: class TradeInCart{
2: Account Account{get;}
3: LineItem Add(
4: Game game,
5: IRepository<QueueHistory> repository,
6: LoggingService service);
7:
8: ValidationResult CanAdd(
9: Game game,
10: IRepository<QueueHistory> repository,
11: LoggingService service);
12:
13: IList<LineItems> LineItems{get;}
14: }
The alternative option is to have a TradeInCartFacade that handles the validations and adding the items to the cart. The façade can have the repository and services injected though DI which is nice, but the big negative is that the cart ends up totally anemic.
Any thought on this would be greatly appreciated.
Thanks, Jesse
As I highlighted above, the thing that will help you with your business rules is to introduce the Customer object (that you probably already have) with the property GamesReportedLost (an IList<Game>). Your TradeInCart would have a reference to the Customer object and could then check the rule in the Add method.
Before I go into the code, it looks like your Account object might be used the same way, but your description of the domain doesn’t mention accounts, so I’m going to assume that that’s unrelated for now:
1: public class Customer{
2:
3: /* other properties and methods */
4:
5: private IList<Game> gamesReportedLost;
6: public virtual IList<Game> GamesReportedLost
7: {
8: get
9: {
10: return gamesReportedLost;
11: }
12: set
13: {
14: gamesReportedLost = value;
15: }
16: }
17: }
Keep in mind that the GamesReportedLost is a persistent property of Customer. Every time a customer reports a game lost, this list needs to be kept up to date. Here’s the TradeInCart now:
1: public class TradeInCart
2: {
3: /* other properties and methods */
4:
5: private Customer customer;
6: public virtual Customer Customer
7: {
8: get { return customer; }
9: set { customer = value; }
10: }
11:
12: private IList<LineItem> lineItems;
13: public virtual IList<LineItem> LineItems
14: {
15: get { return lineItems; }
16: set { lineItems = value; }
17: }
18:
19: public void Add(Game game)
20: {
21: if (lineItems.Count >= CONSTANTS.MaxItemsPerCart)
22: {
23: FailureEvents.RaiseCartIsFullEvent();
24: return;
25: }
26:
27: if (NumberOfGameAlreadyInCart(game) >=
28: CONSTANTS.MaxNumberOfSameGamePerCart)
29: {
30: FailureEvents
31: .RaiseMaxNumberOfSameGamePerCartReachedEvent();
32: return;
33: }
34:
35: if (customer.GamesReportedLost.Contains(game))
36: FailureEvents.RaiseGameReportedLostEvent();
37: else
38: this.lineItems.Add(new LineItem(game));
39: }
40:
41: private int NumberOfGameAlreadyInCart(Game game)
42: {
43: int result = 0;
44:
45: foreach(LineItem li in this.lineItems)
46: if (li.Game == game)
47: result++;
48:
49: return result;
50: }
51: }
52:
53: public static class FailureEvents
54: {
55: public static event EventHandler GameReportedLost;
56: public static void RaiseGameReportedLostEvent()
57: {
58: if (GameReportedLost != null)
59: GameReportedLost(null, null);
60: }
61:
62: public static event EventHandler CartIsFull;
63: public static void RaiseCartIsFullEvent()
64: {
65: if (CartIsFull != null)
66: CartIsFull(null, null);
67: }
68:
69: public static event EventHandler MaxNumberOfSameGamePerCartReached;
70: public static void RaiseMaxNumberOfSameGamePerCartReachedEvent()
71: {
72: if (MaxNumberOfSameGamePerCartReached != null)
73: MaxNumberOfSameGamePerCartReached(null, null);
74: }
75: }
Your service layer class that calls the Add method of TradeInCart would first subscribe to the relevant events in FailureEvents. If one of those events is raised, it would do the necessary logging, external system calls, etc.
As you can see, the API of TradeInCart doesn’t need to make use of any external repositories, nor do you need to inject any other external dependencies in.
One thing I didn’t do in the above code to keep it “short” is to define the relevant custom EventArgs for bubbling up the information as to which game was reported lost or already have 3 of those in the cart. That is something that definitely should be done so that the service layer can pass this information back to the client.
Here’s a look at Service Layer code:
1: public class AddGameToCartMessageHandler :
2: BaseMessageHandler<AddGameToCartMessage>
3: {
4: public override void Handle(AddGameToCartMessage m)
5: {
6: using (ISession session = SessionFactory.OpenSession())
7: using (ITransaction tx = session.BeginTransaction())
8: {
9: TradeInCart cart = session.Get<TradeInCart>(m.CartId);
10: Game g = session.Get<Game>(m.GameId);
11:
12: Domain.FailureEvents.GameReportedLost +=
13: gameReportedLost;
14: Domain.FailureEvents.CartIsFull +=
15: cartIsFull;
16: Domain.FailureEvents.MaxNumberOfSameGamePerCartReached +=
17: maxNumberOfSameGamePerCartReached;
18:
19: cart.Add(g);
20:
21: Domain.FailureEvents.GameReportedLost -=
22: gameReportedLost;
23: Domain.FailureEvents.CartIsFull -=
24: cartIsFull;
25: Domain.FailureEvents.MaxNumberOfSameGamePerCartReached -=
26: maxNumberOfSameGamePerCartReached;
27:
28: tx.Commit();
29: }
30: }
31:
32: private EventHandler gameReportedLost = delegate {
33: Bus.Return((int)ErrorCodes.GameReportedLost);
34: };
35:
36: private EventHandler cartIsFull = delegate {
37: Bus.Return((int)ErrorCodes.CartIsFull);
38: };
39:
40: private EventHandler maxNumberOfSameGamePerCartReached = delegate {
41: Bus.Return((int)ErrorCodes.MaxNumberOfSameGamePerCartReached);
42: };
43: }
44: }
It’s important to remember to clean up your event subscriptions so that your Service Layer objects get garbage collected. This is one of the primary causes of memory leaks when using static events in your Domain Model. I’m hoping to find ways to use lambdas to decrease this repetitive coding pattern. You might be thinking to yourself that non-static events on your Domain Model objects would be easier, since those objects would get collected, freeing up the service layer objects for collection as well. There’s just on small problem:
The problem is that if an event is raised by a child (or grandchild object), the service layer object may not even know that that grandchild was involved and, as such, would not have subscribed to that event. The only way the service layer could work was by knowing how the Domain Model worked internally – in essence, breaking encapsulation.
If you’re thinking that using exceptions would be better, you’d be right in thinking that that won’t break encapsulation, and that you wouldn’t need all that subscribe/unsubscribe code in the service layer. The only problem is that the Domain Model needs to know that the service layer had a default catch clause so that it wouldn’t blow up. Otherwise, the service layer (or WCF, or nServiceBus) may end up flagging that message as a poison message (Read more about poison messages). You’d also have to be extremely careful about in which environments you used your Domain Model – in other words, your reuse is shot.
Conclusion
I never said it would be easy
However, the solution is simple (not complex). The same patterns occur over and over. The design is consistent. By focusing on the dependencies we now have a domain model that is reusable across many environments (server, client, sql clr, silverlight). The domain model is also testable without resorting to any fancy mock objects.
One closing comment – while I do my best to write code that is consistent with production quality environments, this code is more about demonstrating design principles. As such, I focus more on the self-documenting aspects of the code and have elided many production concerns.
Do you have a better solution?
Something that I haven’t considered?
Do me a favour – leave me a comment. Tell me what you think.
Posted in Architecture, Business Rules, DDD, Data Access, Development, OO, Simplicity | 63 Comments »
Friday, February 15th, 2008
I got a question about how to stay away from CRUD based service interfaces when the logic itself is like that, and I’ve found that this shift in thinking really needs more examples, so I’ve decided to put this out there:
For instance, in an HR system, the process of interviewing candidates – wouldn’t you just insert, update, and delete these Appointment objects?
If I were to put on my domain-driven hat, I would describe those requirements differently – interview appointments have a lifecycle: proposed, accepted, cancelled, etc. It seems that only a user of the role HR Interviewer should be able to make appointments for themselves, so the service layer code would probably look something like this:
using (ISession session = SessionFactory.OpenSession())
using (ITransaction tx = session.BeginTransaction())
{
ICandidateInterviewer interviewer = session.Get<ICandidateInterviewer>(message.InterviewerId);
ICandidate candidate = session.Get<ICandidate>(message.CandidateId);
interviewer.ScheduleInterviewWith(candidate).At(message.RequestedTime);
tx.Commit();
}
The “ScheduleInterviewWith” method accepts an ICandidate and returns an IAppointment. IAppointment has a method “At” which accepts a DateTime parameter and returns void – just changes the data of the appointment. The state of the appointment at creation time would probably be proposed. The appointment object would probably be added to the list of appointments for that interviewer – that’s what will cause it to be persisted automatically.
Later, when the candidate accepts the meeting, we could have the following method on ICandidate – void Accept(IAppointment); that would obviously check that the candidate is the right person for that interview, the appointment’s current state (not cancelled), etc – finally updating its state. What part of this looks like create, update, delete? If that’s what your service layer to domain interaction looks like, do you now know what your messages will be looking like?CRUD seems to be what most of us are familiar with. Moving to domain-driven thinking takes time and practice, but is well worth it. Contrast this with a more traditional O/R mapping solution:
using (ISession session = SessionFactory.OpenSession())
using (ITransaction tx = session.BeginTransaction())
{
ICandidateInterviewer interviewer = session.Get<ICandidateInterviewer>(message.InterviewerId);
ICandidate candidate = session.Get<ICandidate>(message.CandidateId);
Appointment a = new Appointment();
a.Interviewer = interviewer;
interviewer.Appointments.Add(a);
a.Candidate = candidate;
candidate.Appointments.Add(a);
a.Time = message.RequestedTime;
session.Save(a);
tx.Commit();
}
As you can see, we’ve got simpler, more expressive, and more testable code when employing the domain model pattern, than using “just” O/R mapping. I’m not saying that the domain model pattern doesn’t need O/R mapping in the background for it to work. But that’s just it – the persistence gunk needs to be in the background and the business logic needs to be encapsulated.
So, while I’ll agree with Dave that the Domain Model is more lifestyle than pattern, I would argue against these conclusions:
If this post had a point, it’s only to share the idea that Domain Model is a big, big thing. It’s probably overkill in a lot of cases where you have simple applications that have very simple purposes.
As you just saw in the example above, there is no “overkill” to be seen. The domain model in the example wasn’t “a big, big thing”.
The domain model. Use it.
Why not have a better lifestyle? 
Posted in ADO.NET, Architecture, DDD, Data Access, Databases, Development, OO, Simplicity | 22 Comments »
Wednesday, September 12th, 2007
In this podcast we’ll try to describe some of the pitfalls of trying to split a domain model between multiple services, as well as how SOA side-steps the “single version of the truth” issue found in reporting.
Rishi asks:
Hi Udi,
First of all, thanks for all the posts and info you share, it is very insightful compared to loads n’ loads of marketing bull and vendor whitepapers. Ok, I have two questions for you.
1. I want to create a SOA-based LOB application/platform and I generally understand the ‘tenets of services’ and reasons for the same. However, as you may well know, there is a lot of interdependency between business constructs (such as a customer with an order, or a delivery with a product construct). Now, should we share these constructs within a tightly-coupled and domain-based “system” which exposes a number of services to the outside world and use the constructs directly inside the so-called “system” boundary. Or on the opposite spectrum have a number of autonomous and independent services that expose, own, and share certain business constructs or at least part of the data that represents them as a whole. For example, an order service will need to interact with a customer construct, which primarily/essentially is (or should be?) owned by a customer profile service – in this context, with clear, direct, and immediate inter-dependency what is preferable? Where do we draw the enclosing line?
2. In a line of business application, reporting and shaping data are a given necessity. Now, with autonomous and independent services which define business constructs in their contextual ways, how do we practically shape, combine, and filter data across various services? We certainly can’t do joins over multiple services in a practical way? And as some suggest, if we are to maintain duplicate or master data elsewhere, it just seems very messy to me – just consider having 3 versions of an order services, with 2 versions of support services, and ‘n’ number of other services to comb data from. Further, for reporting and also analytical purposes we really need to have business data structured in a well-defined manner, which for all purposes needs to be the “single version of the truth”. I can’t see granular services, with all its tenets, sitting nicely with such other requirements of the business – and yet I am not even asking them to be real-time. How do we meet such business requirements in your view with SOA?
Hope the above makes sense!
Cheers,
Rishi
PS: I use the word business construct purposefully, and it does not directly attribute to a well-defined programmable entity (in object-oriented way, that is).
Download via the Dr. Dobb’s site.
Or download directly here.
Additional References
Want more?
Check out the “Ask Udi” archives.
Got a question?
Send Udi your question to answer on the show.
Posted in Architecture, Ask Udi Podcast, DDD, SOA | 6 Comments »
Monday, June 4th, 2007
Some Technical Difficulties
Ayende and I had an email conversation that started with me asking what would happen if I added an Order to a Customer’s “Orders” collection, when that collection was lazy loaded. My question was whether the addition of an element would result in NHibernate hitting the database to fill that collection. His answer was a simple “yes”. In the case where a customer can have many (millions) of Orders, that’s just not a feasible solution. The technical solution was simple – just define the Orders collection on the Customer as “inverse=true”, and then to save a new Order, just write:
session.Save( new Order(myCustomer) );
Although it works, it’s not “DDD compliant”
In Ayende’s post Architecting for Performance he quoted a part of our email conversation. The conclusion I reached was that in order to design performant domain models, you need to know the kinds of data volumes you’re dealing with. It affects both internals and the API of the model – when can you assume cascade, and when not. It’s important to make these kinds of things explicit in the Domain Model’s API.
How do you make “transparent persistence” explicit?
The problem occurs around “transparent persistence”. If we were to assume that the Customer object added the Order object to its Orders collection, then we wouldn’t have to explicitly save orders it creates, so we would write service layer code like this:
using (IDBScope scope = this.DbServices.GetScope(TransactionOption.On))
{
IOrderCreatingCustomer c = this.DbServices.Get<IOrderCreatingCustomer>(msg.CustomerId);
c.CreateOrder(message.OrderAmount);
scope.Complete();
}
On the other hand, if we designed our Domain Model around the million orders constraint, we would need to explicitly save the order, so we would write service layer code like this:
using (IDBScope scope = this.DbServices.GetScope(TransactionOption.On))
{
IOrderCreatingCustomer c = this.DbServices.Get<IOrderCreatingCustomer>(msg.CustomerId);
IOrder o = c.CreateOrder(message.OrderAmount);
this.DbServices.Save(o);
scope.Complete();
}
But the question remains, how do we communicate these guidelines to service layer developers from the Domain Model? There are a number of ways, but it’s important to decide on one and use it consistently. Performance and correctness require it.
Solution 1: Explicitness via Return Type
The first way is a little subtle, but you can do it with the return type of the “CreateOrder” method call. In the case where the Domain Model wishes to communicate that it handles transparent persistence by itself, have the method return “void”. Where the Domain Model wishes to communicate that it will not handle transparent persistence, have the method return the Order object created.
Another way to communicate the fact that an Order has been created that needs to be saved is with events. There are two sub-ways to do so:
Solution 2: Explicitness via Events on Domain Objects
The first is to just define the event on the customer object and have the service layer subscribe to it. It’s pretty clear that when the service layer receives a “OrderCreatedThatRequiresSaving” event, it should save the order passed in the event arguments.
The second realizes that the call to the customer object may come from some other domain object and that the service layer doesn’t necessarily know what can happen as the result of calling some method on the aggregate root. The change of state as the result of that method call may permeate the entire object graph. If each object in the graph raises its own events, its calling object will have to propagate that event to its parent – resulting in defining the same events in multiple places, and each object being aware of all things possible with its great-grandchild objects. That is clearly bad.
What [ThreadStatic] is for
So, the solution is to use thread-static events.
[Sidebar] Thread-static events are just static events defined on a static class, where each event has the ThreadStaticAttribute applied to it. This attribute is important for server-side scenarios where multiple threads will be running through the Domain Model at the same time. The easiest thread-safe way to use static data is to apply the ThreadStaticAttribute.
Solution 3: Explicitness via Static Events
Each object raises the appropriate static event according to its logic. In our example, Customer would call:
DomainModelEvents.RaiseOrderCreatedThatRequiresSavingEvent(newOrder);
And the service layer would write:
DomainModelEvents.OrderCreatedThatRequiresSaving +=
delegate(object sender, OrderEventArgs e) { this.DbServices.Save(e.Order); };
The advantage of this solution is that it requires minimal knowledge of the Domain Model for the Service Layer to correctly work with it. It also communicates that anything that doesn’t raise an event will be persisted transparently behind the appropriate root object.
Statics and Testability
I know that many of you are wondering if I am really advocating the use of statics. The problem with most static classes is that they hurt testability because they are difficult to mock out. Often statics are used as Facades to hide some technological implementation detail. In this case, the static class is an inherent part of the Domain Model and does not serve as a Facade for anything.
When it comes to testing the Domain Model, we don’t have to mock anything out since the Domain Model is independent of all other concerns. This leaves us with unit testing at the single Domain Class level, which is pretty useless unless we’re TDD-ing the design of the Domain Model, in which case we’ll still be fiddling around with a bunch of classes at a time. Domain Models are best tested using State-Based Testing; get the objects into a given state, call a method on one of them, assert the resulting state. The static events don’t impede that kind of testing at all.
What if we used Injection instead of Statics?
Also, you’ll find that each Service Layer class will need to subscribe to all the Domain Model’s events, something that is easily handled by a base class. I will state that I have tried doing this without a static class, and injecting that singleton object into the Service Layer classes, and in that setter having them subscribe to its events. This was also pulled into a base class. The main difference was that the Dependency Injection solution required injecting that object into Domain Objects as well. Personally, I’m against injection for domain objects. So all in all, the static solution comes with less overhead than that based on injection.
Summary
In summary, beyond the “technical basics” of being aware of your data volumes and designing your Domain Model to handle each use case performantly, I’ve found these techniques useful for designing its API as well as communicating my intent around persistence transparency. So give it a try. I’d be grateful to hear your thoughts on the matter as well as what else you’ve found that works.
Related posts:
Posted in Architecture, Business Rules, DDD, Data Access, Databases, Dependency Injection, Development, NHibernate, OO, Performance, Simplicity, TDD, Testing, Threading | 14 Comments »
Sunday, May 20th, 2007
First I find out that NHibernate does support “Persistence by Reachability”, even though the docs say it doesn’t. Next, Ayende makes it support multiple queries in a single DB roundtrip, something I’ve been asking all the other O/R mappers out there to do. To top it off, he’s got his sights set on solving the issues I raised in my talk on Complex Business Logic with DDD and O/R Mapping at DevTeach. That’s right, he’s going to give me my decorators and state machines.
I love you, Oren.
I know that the ADO.NET Entity Framework guys are open to this as well, but I’m pretty sure that the “Entity Model” thinking will hold them back. You just can’t divorce data and behavior – not when employing state machines or decorators.
I’m sold.
Posted in ADO.NET, Architecture, Business Rules, DDD, Data Access, Databases, NHibernate, OO | No Comments »
|
|
|
Recommendations
Bryan Wheeler, Director Platform Development at msnbc.com
“ Udi Dahan is the real deal.We brought him on site to give our development staff the 5-day “Advanced Distributed System Design” training. The course profoundly changed our understanding and approach to SOA and distributed systems. Consider some of the evidence: 1. Months later, developers still make allusions to concepts learned in the course nearly every day 2. One of our developers went home and made her husband (a developer at another company) sign up for the course at a subsequent date/venue 3. Based on what we learned, we’ve made constant improvements to our architecture that have helped us to adapt to our ever changing business domain at scale and speed If you have the opportunity to receive the training, you will make a substantial paradigm shift. If I were to do the whole thing over again, I’d start the week by playing the clip from the Matrix where Morpheus offers Neo the choice between the red and blue pills. Once you make the intellectual leap, you’ll never look at distributed systems the same way. Beyond the training, we were able to spend some time with Udi discussing issues unique to our business domain. Because Udi is a rare combination of a big picture thinker and a low level doer, he can quickly hone in on various issues and quickly make good (if not startling) recommendations to help solve tough technical issues.” November 11, 2010
Sam Gentile, Independent WCF & SOA Expert
“Udi, one of the great minds in this area. A man I respect immensely.”
Ian Robinson, Principal Consultant at ThoughtWorks
"Your blog and articles have been enormously useful in shaping, testing and refining my own approach to delivering on SOA initiatives over the last few years. Over and against a certain 3-layer-application-architecture-blown-out-to- distributed-proportions school of SOA, your writing, steers a far more valuable course."
Shy Cohen, Senior Program Manager at Microsoft
“Udi is a world renowned software architect and speaker. I met Udi at a conference that we were both speaking at, and immediately recognized his keen insight and razor-sharp intellect. Our shared passion for SOA and the advancement of its practice launched a discussion that lasted into the small hours of the night. It was evident through that discussion that Udi is one of the most knowledgeable people in the SOA space. It was also clear why – Udi does not settle for mediocrity, and seeks to fully understand (or define) the logic and principles behind things. Humble yet uncompromising, Udi is a pleasure to interact with.”
Glenn Block, Senior Program Manager - WCF at Microsoft
“I have known Udi for many years having attended his workshops and having several personal interactions including working with him when we were building our Composite Application Guidance in patterns & practices. What impresses me about Udi is his deep insight into how to address business problems through sound architecture. Backed by many years of building mission critical real world distributed systems it is no wonder that Udi is the best at what he does. When customers have deep issues with their system design, I point them Udi's way.”
Karl Wannenmacher, Senior Lead Expert at Frequentis AG
“I have been following Udi’s blog and podcasts since 2007. I’m convinced that he is one of the most knowledgeable and experienced people in the field of SOA, EDA and large scale systems.
Udi helped Frequentis to design a major subsystem of a large mission critical system with a nationwide deployment based on NServiceBus. It was impressive to see how he took the initial architecture and turned it upside down leading to a very flexible and scalable yet simple system without knowing the details of the business domain.
I highly recommend consulting with Udi when it comes to large scale mission critical systems in any domain.”
Simon Segal, Independent Consultant
“Udi is one of the outstanding software development minds in the world today, his vast insights into Service Oriented Architectures and Smart Clients in particular are indeed a rare commodity. Udi is also an exceptional teacher and can help lead teams to fall into the pit of success. I would recommend Udi to anyone considering some Architecural guidance and support in their next project.”
Ohad Israeli, Chief Architect at Hewlett-Packard, Indigo Division
“When you need a man to do the job Udi is your man! No matter if you are facing near deadline deadlock or at the early stages of your development, if you have a problem Udi is the one who will probably be able to solve it, with his large experience at the industry and his widely horizons of thinking , he is always full of just in place great architectural ideas.
I am honored to have Udi as a colleague and a friend (plus having his cell phone on my speed dial).”
Ward Bell, VP Product Development at IdeaBlade
“Everyone will tell you how smart and knowledgable Udi is ... and they are oh-so-right. Let me add that Udi is a smart LISTENER. He's always calibrating what he has to offer with your needs and your experience ... looking for the fit. He has strongly held views ... and the ability to temper them with the nuances of the situation. I trust Udi to tell me what I need to hear, even if I don't want to hear it, ... in a way that I can hear it. That's a rare skill to go along with his command and intelligence.”
Eli Brin, Program Manager at RISCO Group
“We hired Udi as a SOA specialist for a large scale project. The development is outsourced to India. SOA is a buzzword used almost for anything today. We wanted to understand what SOA really is, and what is the meaning and practice to develop a SOA based system.
We identified Udi as the one that can put some sense and order in our minds. We started with a private customized SOA training for the entire team in Israel. After that I had several focused sessions regarding our architecture and design.
I will summarize it simply (as he is the software simplist): We are very happy to have Udi in our project. It has a great benefit. We feel good and assured with the knowledge and practice he brings. He doesn’t talk over our heads. We assimilated nServicebus as the ESB of the project. I highly recommend you to bring Udi into your project.”
Catherine Hole, Senior Project Manager at the Norwegian Health Network
“My colleagues and I have spent five interesting days with Udi - diving into the many aspects of SOA. Udi has shown impressive abilities of understanding organizational challenges, and has brought the business perspective into our way of looking at services. He has an excellent understanding of the many layers from business at the top to the technical infrstructure at the bottom. He is a great listener, and manages to simplify challenges in a way that is understandable both for developers and CEOs, and all the specialists in between.”
Yoel Arnon, MSMQ Expert
“Udi has a unique, in depth understanding of service oriented architecture and how it should be used in the real world, combined with excellent presentation skills. I think Udi should be a premier choice for a consultant or architect of distributed systems.”
Vadim Mesonzhnik, Development Project Lead at Polycom
“When we were faced with a task of creating a high performance server for a video-tele conferencing domain we decided to opt for a stateless cluster with SQL server approach. In order to confirm our decision we invited Udi.
After carefully listening for 2 hours he said: "With your kind of high availability and performance requirements you don’t want to go with stateless architecture."
One simple sentence saved us from implementing a wrong product and finding that out after years of development. No matter whether our former decisions were confirmed or altered, it gave us great confidence to move forward relying on the experience, industry best-practices and time-proven techniques that Udi shared with us.
It was a distinct pleasure and a unique opportunity to learn from someone who is among the best at what he does.”
Jack Van Hoof, Enterprise Integration Architect at Dutch Railways
“Udi is a respected visionary on SOA and EDA, whose opinion I most of the time (if not always) highly agree with. The nice thing about Udi is that he is able to explain architectural concepts in terms of practical code-level examples.”
Neil Robbins, Applications Architect at Brit Insurance
“Having followed Udi's blog and other writings for a number of years I attended Udi's two day course on 'Loosely Coupled Messaging with NServiceBus' at SkillsMatter, London.
I would strongly recommend this course to anyone with an interest in how to develop IT systems which provide immediate and future fitness for purpose. An influential and innovative thought leader and practitioner in his field, Udi demonstrates and shares a phenomenally in depth knowledge that proves his position as one of the premier experts in his field globally.
The course has enhanced my knowledge and skills in ways that I am able to immediately apply to provide benefits to my employer. Additionally though I will be able to build upon what I learned in my 2 days with Udi and have no doubt that it will only enhance my future career.
I cannot recommend Udi, and his courses, highly enough.”
Nick Malik, Enterprise Architect at Microsoft Corporation
“ You are an excellent speaker and trainer, Udi, and I've had the fortunate experience of having attended one of your presentations. I believe that you are a knowledgable and intelligent man.”
Sean Farmar, Chief Technical Architect at Candidate Manager Ltd
“Udi has provided us with guidance in system architecture and supports our implementation of NServiceBus in our core business application.
He accompanied us in all stages of our development cycle and helped us put vision into real life distributed scalable software. He brought fresh thinking, great in depth of understanding software, and ongoing support that proved as valuable and cost effective.
Udi has the unique ability to analyze the business problem and come up with a simple and elegant solution for the code and the business alike. With Udi's attention to details, and knowledge we avoided pit falls that would cost us dearly.”
Børge Hansen, Architect Advisor at Microsoft
“Udi delivered a 5 hour long workshop on SOA for aspiring architects in Norway. While keeping everyone awake and excited Udi gave us some great insights and really delivered on making complex software challenges simple. Truly the software simplist.”
Motty Cohen, SW Manager at KorenTec Technologies
“I know Udi very well from our mutual work at KorenTec. During the analysis and design of a complex, distributed C4I system - where the basic concepts of NServiceBus start to emerge - I gained a lot of "Udi's hours" so I can surely say that he is a professional, skilled architect with fresh ideas and unique perspective for solving complex architecture challenges. His ideas, concepts and parts of the artifacts are the basis of several state-of-the-art C4I systems that I was involved in their architecture design.”
Aaron Jensen, VP of Engineering at Eleutian Technology
“ Awesome. Just awesome.
We’d been meaning to delve into messaging at Eleutian after multiple discussions with and blog posts from Greg Young and Udi Dahan in the past. We weren’t entirely sure where to start, how to start, what tools to use, how to use them, etc. Being able to sit in a room with Udi for an entire week while he described exactly how, why and what he does to tackle a massive enterprise system was invaluable to say the least.
We now have a much better direction and, more importantly, have the confidence we need to start introducing these powerful concepts into production at Eleutian.”
Gad Rosenthal, Department Manager at Retalix
“A thinking person. Brought fresh and valuable ideas that helped us in architecting our product. When recommending a solution he supports it with evidence and detail so you can successfully act based on it. Udi's support "comes on all levels" - As the solution architect through to the detailed class design. Trustworthy!”
Chris Bilson, Developer at Russell Investment Group
“I had the pleasure of attending a workshop Udi led at the Seattle ALT.NET conference in February 2009. I have been reading Udi's articles and listening to his podcasts for a long time and have always looked to him as a source of advice on software architecture. When I actually met him and talked to him I was even more impressed. Not only is Udi an extremely likable person, he's got that rare gift of being able to explain complex concepts and ideas in a way that is easy to understand. All the attendees of the workshop greatly appreciate the time he spent with us and the amazing insights into service oriented architecture he shared with us.”
Alexey Shestialtynov, Senior .Net Developer at Candidate Manager
“I met Udi at Candidate Manager where he was brought in part-time as a consultant to help the company make its flagship product more scalable. For me, even after 30 years in software development, working with Udi was a great learning experience. I simply love his fresh ideas and architecture insights. As we all know it is not enough to be armed with best tools and technologies to be successful in software - there is still human factor involved. When, as it happens, the project got in trouble, management asked Udi to step into a leadership role and bring it back on track. This he did in the span of a month. I can only wish that things had been done this way from the very beginning. I look forward to working with Udi again in the future.”
Christopher Bennage, President at Blue Spire Consulting, Inc.
“My company was hired to be the primary development team for a large scale and highly distributed application. Since these are not necessarily everyday requirements, we wanted to bring in some additional expertise. We chose Udi because of his blogging, podcasting, and speaking. We asked him to to review our architectural strategy as well as the overall viability of project.
I was very impressed, as Udi demonstrated a broad understanding of the sorts of problems we would face. His advice was honest and unbiased and very pragmatic. Whenever I questioned him on particular points, he was able to backup his opinion with real life examples.
I was also impressed with his clarity and precision. He was very careful to untangle the meaning of words that might be overloaded or otherwise confusing. While Udi's hourly rate may not be the cheapest, the ROI is undoubtedly a deal.
I would highly recommend consulting with Udi.”
Robert Lewkovich, Product / Development Manager at Eggs Overnight
“Udi's advice and consulting were a huge time saver for the project I'm responsible for. The $ spent were well worth it and provided me with a more complete understanding of nServiceBus and most importantly in helping make the correct architectural decisions earlier thereby reducing later, and more expensive, rework.”
Ray Houston, Director of Development at TOPAZ Technologies
“Udi's SOA class made me smart - it was awesome.
The class was very well put together. The materials were clear and concise and Udi did a fantastic job presenting it. It was a good mixture of lecture, coding, and question and answer. I fully expected that I would be taking notes like crazy, but it was so well laid out that the only thing I wrote down the entire course was what I wanted for lunch. Udi provided us with all the lecture materials and everyone has access to all of the samples which are in the nServiceBus trunk.
Now I know why Udi is the "Software Simplist." I was amazed to find that all the code and solutions were indeed very simple. The patterns that Udi presented keep things simple by isolating complexity so that it doesn't creep into your day to day code. The domain code looks the same if it's running in a single process or if it's running in 100 processes.”
Ian Cooper, Team Lead at Beazley
“Udi is one of the leaders in the .Net development community, one of the truly smart guys who do not just get best architectural practice well enough to educate others but drives innovation. Udi consistently challenges my thinking in ways that make me better at what I do.”
Liron Levy, Team Leader at Rafael
“I've met Udi when I worked as a team leader in Rafael. One of the most senior managers there knew Udi because he was doing superb architecture job in another Rafael project and he recommended bringing him on board to help the project I was leading. Udi brought with him fresh solutions and invaluable deep architecture insights. He is an authority on SOA (service oriented architecture) and this was a tremendous help in our project. On the personal level - Udi is a great communicator and can persuade even the most difficult audiences (I was part of such an audience myself..) by bringing sound explanations that draw on his extensive knowledge in the software business. Working with Udi was a great learning experience for me, and I'll be happy to work with him again in the future.”
Adam Dymitruk, Director of IT at Apara Systems
“I met Udi for the first time at DevTeach in Montreal back in early 2007. While Udi is usually involved in SOA subjects, his knowledge spans all of a software development company's concerns. I would not hesitate to recommend Udi for any company that needs excellent leadership, mentoring, problem solving, application of patterns, implementation of methodologies and straight out solution development. There are very few people in the world that are as dedicated to their craft as Udi is to his. At ALT.NET Seattle, Udi explained many core ideas about SOA. The team that I brought with me found his workshop and other talks the highlight of the event and provided the most value to us and our organization. I am thrilled to have the opportunity to recommend him.”
Eytan Michaeli, CTO Korentec
“Udi was responsible for a major project in the company, and as a chief architect designed a complex multi server C4I system with many innovations and excellent performance.”
Carl Kenne, .Net Consultant at Dotway AB
“Udi's session "DDD in Enterprise apps" was truly an eye opener. Udi has a great ability to explain complex enterprise designs in a very comprehensive and inspiring way. I've seen several sessions on both DDD and SOA in the past, but Udi puts it in a completly new perspective and makes us understand what it's all really about. If you ever have a chance to see any of Udi's sessions in the future, take it!”
Avi Nehama, R&D Project Manager at Retalix
“Not only that Udi is a briliant software architecture consultant, he also has remarkable abilities to present complex ideas in a simple and concise manner, and...
always with a smile. Udi is indeed a top-league professional!”
Ben Scheirman, Lead Developer at CenterPoint Energy
“Udi is one of those rare people who not only deeply understands SOA and domain driven design, but also eloquently conveys that in an easy to grasp way. He is patient, polite, and easy to talk to. I'm extremely glad I came to his workshop on SOA.”
Scott C. Reynolds, Director of Software Engineering at CBLPath
“Udi is consistently advancing the state of thought in software architecture, service orientation, and domain modeling.
His mastery of the technologies and techniques is second to none, but he pairs that with a singular ability to listen and communicate effectively with all parties, technical and non, to help people arrive at context-appropriate solutions.
Every time I have worked with Udi, or attended a talk of his, or just had a conversation with him I have come away from it enriched with new understanding about the ideas discussed.”
Evgeny-Hen Osipow, Head of R&D at PCLine
“Udi has helped PCLine on projects by implementing architectural blueprints demonstrating the value of simple design and code.”
Rhys Campbell, Owner at Artemis West
“For many years I have been following the works of Udi. His explanation of often complex design and architectural concepts are so cleanly broken down that even the most junior of architects can begin to understand these concepts. These concepts however tend to typify the "real world" problems we face daily so even the most experienced software expert will find himself in an "Aha!" moment when following Udi teachings.
It was a pleasure to finally meet Udi in Seattle Alt.Net OpenSpaces 2008, where I was pleasantly surprised at how down-to-earth and approachable he was. His depth and breadth of software knowledge also became apparent when discussion with his peers quickly dove deep in to the problems we current face. If given the opportunity to work with or recommend Udi I would quickly take that chance. When I think .Net Architecture, I think Udi.”
Sverre Hundeide, Senior Consultant at Objectware
“Udi had been hired to present the third LEAP master class in Oslo. He is an well known international expert on enterprise software architecture and design, and is the author of the open source messaging framework nServiceBus.
The entire class was based on discussion and interaction with the audience, and the only Power Point slide used was the one showing the agenda.
He started out with sketching a naive traditional n-tier application (big ball of mud), and based on suggestions from the audience we explored different solutions which might improve the solution. Whatever suggestions we threw at him, he always had a thoroughly considered answer describing pros and cons with the suggested solution. He obviously has a lot of experience with real world enterprise SOA applications.”
Raphaël Wouters, Owner/Managing Partner at Medinternals
“I attended Udi's excellent course 'Advanced Distributed System Design with SOA and DDD' at Skillsmatter. Few people can truly claim such a high skill and expertise level, present it using a pragmatic, concrete no-nonsense approach and still stay reachable.”
Nimrod Peleg, Lab Engineer at Technion IIT
“One of the best programmers and software engineer I've ever met, creative, knows how to design and implemet, very collaborative and finally - the applications he designed implemeted work for many years without any problems!”
Jose Manuel Beas
“When I attended Udi's SOA Workshop, then it suddenly changed my view of what Service Oriented Architectures were all about. Udi explained complex concepts very clearly and created a very productive discussion environment where all the attendees could learn a lot. I strongly recommend hiring Udi.”
Daniel Jin, Senior Lead Developer at PJM Interconnection
“Udi is one of the top SOA guru in the .NET space. He is always eager to help others by sharing his knowledge and experiences. His blog articles often offer deep insights and is a invaluable resource. I highly recommend him.”
Pasi Taive, Chief Architect at Tieto
“I attended both of Udi's "UI Composition Key to SOA Success" and "DDD in Enterprise Apps" sessions and they were exceptionally good. I will definitely participate in his sessions again. Udi is a great presenter and has the ability to explain complex issues in a manner that everyone understands.”
Eran Sagi, Software Architect at HP
“So far, I heard about Service Oriented architecture all over.
Everyone mentions it – the big buzz word.
But, when I actually asked someone for what does it really mean, no one managed to give me a complete satisfied answer.
Finally in his excellent course “Advanced Distributed Systems”, I got the answers I was looking for.
Udi went over the different motivations (principles) of Services Oriented, explained them well one by one, and showed how each one could be technically addressed using NService bus.
In his course, Udi also explain the way of thinking when coming to design a Service Oriented system.
What are the questions you need to ask yourself in order to shape your system, place the logic in the right places for best Service Oriented system.
I would recommend this course for any architect or developer who deals with distributed system, but not only.
In my work we do not have a real distributed system, but one PC which host both the UI application and the different services inside, all communicating via WCF.
I found that many of the architecture principles and motivations of SOA apply for our system as well. Enough that you have SW partitioned into components and most of the principles becomes relevant to you as well.
Bottom line – an excellent course recommended to any SW Architect, or any developer dealing with distributed system.”
Consult with Udi
Guest Authored Books
|