Tuesday 27 October 2009

Commands and Events

In my last post I ended with talking about sending messages between bounded contexts. In this post I want to describe how to do this, but I also want to talk about a new thing I want to try out. It is called Command and Query Responsibility Segregation (CQRS).

Please leave a message to tell me if you understand it or not?

With CQRS you are basically splitting the commands from the queries (Inserts, updates, deletes from the selects :)). This means that we can optimise how we show data on the user interface and how we handle changes.

From the user interface we send "Commands" to the domain. These commands will modify the aggregate roots and save the changes. These changes are translated into "Events" which are saved. When we want to get our aggregate root, we simple have to playback all the events to get our state. This means we have a nice log of what has happened with the object.

An example

"Ok, sounds nice, but how does it work?" you may say.. Lets look at a simplified example:
The user wants to create a new radio program into the system. After clicking on the "New" button, the UI does something like:
_commandBus.Send(new CreateRadioProgramCommand(Guid.NewGuid(), _programName));

In the domain we have a CreateRadioProgramCommandHandler class which will create a new RadioProgram object and save it to the Repository.
While creating the RadioProgram a CreateRadioProgramEvent will be created. This event will be saved in the database and will be published. By publishing the event the event can be used to update the query cache so that the user can find the RadioProgram in the user interface.

Updating the radio

Now that we have a Radio Program, the user can use the user interface to change details of the Radio Program. So when we have changed things, the UI does something like:
_commandBus.Send(new ChangeRadioProgramLanguage(_id, "Dutch"));

The ChangeRadioProgramLanguageCommandHandler will ask the repository for the correct radio program. The repository will get all previous events and use those to construct the Radio Program.
Then the Language will be changed and the Radio Program will be saved.
This causes a new event, LanguageChangedEvent and this event will be published so that the UI cache will be changed.

Communicating with Bounded Contexts?

At this point I am not really curtain how the communication between Bounded Contexts can be established. I think it could be both "Events" AND "Commands" or "Events" that are leading to "Commands"

Wednesday 21 October 2009

NetworkMonitor: my new view of the structure

During the last few weeks I have been reading a lot about software architecture and how other people do things. I found out that it is very easy to create a publish/subscribe system that makes it easy to send messages from one place of the system to somewhere else. I see it as an ideal method to communicate between Bounded Contexts.
With this knowledge I was thinking about how I can structure NetworkMonitor in a loosely coupled way.
  • Scheduler
  • Command runner
  • Host/Service state

Scheduler

The scheduler has the important task to keep a list of scheduled items, this can domain specific things like running commands to check the state of host/services, but also application things like do a log rotation.. The Scheduler can be very generic so that it supports a lot of different items.

Command runner

The command runner will do the actual actions for getting the state of hosts/services. It will run the command and wait for the response, the response will be parsed and the state of the host or service will be set.

Host/Service state

The state of hosts or services can be very simple, but when the state changes to an unexpected state, several things should be done. The Host/Service state has the responsibility to schedule new commands based on the current state, and will be used to show the user the state information.

The missing link

The three subsystems are very different from each other, but they should still communicate with each other. The problem here is how do they communicate.
Before we can answer that we should know where each part is in the system.
I see three possibilities:
  • They are all in the same application
  • They are in different applications on the same computer
  • They are on different places in the network/world
When we choose for only the first option, it will be easy. We can use simple event (like windows messaging or .net events), but this won't work when we need to support the other solutions.
The other two solutions need some kind of messaging system over the network/memory. The same method we can use when we have all the systems in the same application.
What I am thinking about is a Publish/Subscribe pattern.
In short the pattern has one class where all publishers post messages to, and everyone that want to respond on a message, adds(subscribes) itself as listener to that same class. When a message is send, the class will go over every listener and post the message.
How this is done over a network I am not sure yet, but I think it should be possible.

That it for this moment.. I've got a lot of ideas and will try to implement them. But first I have to do some work...

Wednesday 14 October 2009

Resources I find usefull

in the past two or three years, since I am graduated, I am on a constant search for better and new ways of doing things. Most of the information I find in blogs, articles and sometimes in books. (I am not really networking yet, shame on me...)

Here is a list of resources I found useful in no particular order:

EBook:
Foundations of programming: I think this is a collection of blog posts that describe a lot of basic principles.


Books:
Domain Driven Design by Eric Evans: this is a complex abstract book, but once you read it a few times, it is a valuable source.
Applying UML and Patterns by Craig Larman: a good book to get into "modern" object oriented software development. Sometimes I think there is to much information in the book.
Patterns of Enterprise Application Architecture by Martin Fowler: The latest addition in my collection, it describes a lot of patterns that could be used in applications. I like to have a book where I can find the information I need.
The Pragmatic Programmer: This book gives a nice view on what programmers are and how to use the tools they have.

Websites/Blogs:
http://www.infoq.com/: News, Articles, Presentations and ebooks about software development. for the ebooks registration is required...
http://dddstepbystep.com/: information about Domain Driven Design.
http://codebetter.com/
http://devlicious.com/
http://www.lostechies.com/
http://www.udidahan.com/?blog=true
http://martinfowler.com/bliki/

Bounded Context

Sometimes aspects of a domain can have slightly different meanings within different parts of that domain.
When we talk about a radio program this can have different meanings for different people and applications. For one program it means something that a producer makes and that has content like talk and music, in an other part of the organisation it could just mean a file that should be transferred to the right place, yet another part of the organisation sees it as something that should be aired.
Still they are all related.
Of course we could put them all in the same domain, but then people don't understand the software completely. By putting them all in a separate domain, a bounded context, it will become more clear how relations go. This way the people who air the radio program don't have to know that that same radio program has a relationship with a producer.

Another reason to introduce bounded contexts is when the domain is getting to big and to complex. It will pay of to put split the domain in multiple bounded contexts.

But there should be a way to connect these bounded contexts. This can be done in several ways. One way is to write a layer between both domains that convert from one domain to an other.
An other way is to use messages and ask for information. This method I will explain in more detail in the next post when I talk about a new idea for the network monitor system.

Tuesday 13 October 2009

Domain Driven Design and Time based tasks

In one of the projects I worked on, there were a lot of actions that happened at specific times. At midnight the logs would be rotated, an hour past midnight things where rescheduled and checked. at a specific point in the schedule, that item was processed.

With Domain Driven Design it is not obvious how to implement this. Normally we don't have timers in the domain. First of all it is not easy to test timers and their events and secondly, it is not the responsibility of the domain to get the current time and initiate actions.
So how can we do it then? What I am about to write is something I didn't try, but it basically 'popped up' in my head.

A timer is in terms of DDD just an external service. Every time it needs to fire an event, or the time is changing, it will send a message to the domain. So basically it is like a heartbeat. (During my graduation we had a program which controlled a robot, and that program also had a heartbeat to let the robot make decisions...)

In the domain we can have classes like Schedule,which has a method that can receive the current date and time. When this method is called, the schedule will look to the scheduled actions that should be run at that time and will fire events to initiate the actions.
These events can go from one domain to another (bounded contexts, did I already speak about that? if not I will try to do that soon), or from one application to another. We can also store the events that come in and go out, so that we have a history of what happend.

How do the events look like? I think of them like normal objects that contains information about the actions.

I understand that the above is a bid abstract, but it came to my while I was reading different articles about Event Sourcing, Command Query Seperation and other things over the last view days, and now I had the feeling that I should put this in some sort of writing to remember it.

Monday 12 October 2009

Domain / UI speration

On the current project the decision was made to use domain objects directly in the user interface. It seemed to be a good idea at first, it made a lot of code unnecessary, but there where some things that were not solved nicely.

DataBinding

An option that we have in .NET is databinding. this means that we can bind properties to controls and let the control update it self when a specific property is changed. There are also collections that can be bound to objects and that can react to changes from their items.

In our domain we basically have items which have a description and a price. Each item can have subitems (but this isn't necessary) and when there are subitems, the price of the item is the total of the subitems.
The way the domain was set up was that the total price was calculated as soon as the list was changed. We responded to the ListChanged event, calculated the total and set the Price property.

This worked fine, the User interface was getting changed and everybody was happy, but we didn't have any persistence at that moment.

Persistence

When I was implementing/configuring the persistence for our domain, I came across a few problems. First of all the BindingList<> object we used for the subitems was not supported by the framework we use (NHibernate), so we had a choice to make: Implement a custom collection or add extra properties for the BindingList (one exposing the BindingList<>, an other exposing a normal IList<> which could be handled by NHibernate). We went for the custom collection. this went fine for a lot of things, except for the price totals.
When an Item is loaded from the database, a few things happen:
  • an Item object is created
  • a list with for subitems is created
  • eventhandlers are coupled to the list
  • NHibernate sets every property that is mapped, including the list
The last step was deadly for our domain logic. at the moment the list of subitems is set, the event handlers still refer to the old list. This means that when a subitem changes or subitems are added/removed the event handler will NOT pick this up and the total price will not be changed.

Solution

The solution is pretty straight forward, but is a change of thinking. Instead of setting the total price, ask for the total price. So we do "SubItems.Sum(x => x.Price)" in the getter of Item.Price. This way we eliminate the need of a BindingList and event handlers and we can save and load everything.
This gives us another problem. A grid with SubItems will not automatically refresh. This can be solved by add a special Item to the view, ItemView or ItemPresenter or ItemPresentation or whatever, this class should have the logic to drive the User Interface and tell the user interface to change when something important happend. Because this class needs domain logic I did make a subclass for this and I map all the values from one class to the other. (in other cases I just change/use the base class directly, so instead of using a subclass it is a gateway)

This seems to be a lot of extra work, and it is, but I think it is worth the trouble and there are a lot of libraries that can ease the pain. (such as automapper which can map two objects to each other by copying all the values of the properties from one object to the other)
Adding these View classes will make the actual UI code easier to read (and write)

I will try to investigate more about UI patterns, and hope to write down more.