Think Before Coding

To content | To menu | To search

Wednesday, October 28, 2009

Uniqueness validation in CQRS Architecture

This is a short follow up on Bjarte’s Post.

There’s an important thing to consider when needing set validation : why ?

Why do these things need to be considered together and cannot just be handled separately ?

We can distinct two different parameters in uniqueness, Cardinality and Scope.

Cardinality

There are mainly two types of cardinality :

1 Cardinality

Only one employee can be the boss.

The model could provide a IsBoss property on every employee… But constancy would be very hard to achieve, especially in a CQRS architecture.

We should read the preceding rule as :

The company has only one boss. The boss is an employee.

Now, we can model a Boss property on the Company Aggregate Root that will reference the employee that is the boss. Changing the boss can now be an atomic and consistent operation.

We can see that we had to introduce a upper level to manage it (we’ll se it in the Scope section).

n Cardinality

Employee should have different user names.

We can clearly see here that user names must be different because they’ll act as identifiers. This is the goal of almost any uniqueness constraint. The property will be used as a key in a lookup.

The 1 (or 2 or 3) cardinality also act this way. It’s a way to tag an entity. You can ask “who is the boss ?” and get the answer by a simple lookup at the Boss property that acts like a bucket in a hash table.

Scope

There is no such thing as global scope

Even when we say, “Employee should have different user names”, there is a implicit scope, the Company.

Even when we say, “You Id Card number should be unique”, understand, “at the Country scope”.

Even when we say, “Your DNA should be unique”, understand, “At our life understanding scope”.

Find the scope and see the volume of data whose uniqueness should be enforced.

As we said, properties that have a uniqueness constraint are usually used as lookup values to find those entities. As such they rarely take part in the child entity domain logic.

Instead of having a UserName property on the Employee entity, why not have a UserNames key/value collection on the Company that will give the Employee for a given user name ?

If the expected Employee count is expected to be in a limited range, this is the most appropriate solution.

If the number can grow, loading it in memory on each Company hydratation is a bit heavy, so keep the directory on disk (using a table with a unique key in a RDBMS as suggested by Bjarte) or any other way that provide the expected performance.

Conclusion

In every case, when a uniqueness constraint appear on a property, the property does not belong the the entity itself but should be viewed as a key to access the entity from the upper level scope.

Do you have examples that cannot be solved this way ?

Thursday, October 22, 2009

C# Static interfaces - Take 2

As Romain was pointing in the comments, I totally missed to tell where I wanted to go with this static interface things. Need more sleep these days…

So here it is.

No I don’t want to do this

The point was not to enable something like this :

   int value = ICountable.Count;

Static interfaces have no implementation exactly like interfaces.

With interfaces, you need an instance (usually in a variable or member) to find the actual implementation and call it. With static interfaces, you need a type.

There are two ways to specify a type:

  • with its type name (Sample4.Count)
  • with a generic type parameter (T.Count)

I was also proposing a way to specify a type for extension methods.

Where it would be useful - operators

The reason why everybody is asking for static members in interfaces is ultimately to have operators in interfaces.

Imagine :

    public static interface IArithmetic<T>

    {

        static T operator +(T x, T y);

        static T operator -(T x, T y);

        static T operator *(T x, T y);

        static T operator /(T x, T y);

    }

Now you can write generic code like :

        public static T Power<T>(this T value, int count) where T : IArithmetic<T>

        {

            var result = T.Identity;

 

            for (int i=0;i<count;i++)

                result = result*value;

 

            return result;

        }

Cool !

This way, no need for the 20 overloads of Enumerable.Sum, it would work for any type presenting the expected static interface.

Wednesday, October 21, 2009

C# Static interfaces

No DDD today, let’s talk a bit about our favorite language after a short night (I should really tell my neighbors that 3am is not the good time to move their furniture all around the flat).

You can find requests for static methods in interfaces all over the internet..

But there are good reasons not to.

According to Eric Lippert, the main reasons is the difference in inheritance between static methods and instance method du to the absence of shared slots between static methods.

Mixing both static methods and instance methods in interfaces would lead to a real nightmare when you try to understand what really happens.

But why does this question arise so often then ? What’s really needed ?

Static classes as type instances

Let’s take a simple class with both static and instance members :

    class Sample

    {

        // static part

        private static int count;

        public static int Count { get { return count; } }

 

        // instance part

 

        private readonly string name;

 

        public Sample(string name) { this.name = name; }

 

        public void Method()

        {

            count++;

            Console.WriteLine("Total count {0} incremented by {1}", count, name);

        }

    }

Here, Count is a static Property. Static part is different from instance part in that static part exist only once per type.

But we could see static part as being an object with reference is type name.

Why would these object not have interfaces ?

Let refactor this a bit :

 

    public class Sample2

    {

        public sealed class Sample2Class

        {

            internal int count;

            public int Count { get { return count; } }

        }

        public static readonly Sample2Class Class = new Sample2Class();

 

        private readonly string name;

 

        public Sample2(string name)

        {

            this.name = name;

        }

 

        public void Method()

        {

            Class.count++;

            Console.WriteLine("Total count {0} incremented by {1}", Class.count, name);

        }

    }

Here, the only static member is Class, that acts as a singleton for the type. Note that I had to change the count modifier to internal. The behavior is not the same, but it’s conceptually equivalent.

We can make something less extreme :

 

    public class Sample3

    {

        private static int count;

        public static int Count { get { return count; } }

 

        private readonly string name;

 

        public static readonly Sample3Class Class = new Sample3Class();

 

        public sealed class Sample3Class

        {

            public int Count { get { return Sample3.Count; } }

        }

 

        public Sample3(string name) { this.name = name; }

 

        public void Method()

        {

            count++;

            Console.WriteLine("Total count {0} incremented by {1}", count, name);

        }

    }

 

Here, we added only a proxy of public methods and properties on the singleton class.

We could define an interface that would be implemented by Sample3Class that would provide the missing slot concept that Eric Lipperts talk about.

We can also see here that there is no point mixing static and instance method in interface since inheritance rules differs.

Static Interface

Imagination at work. Let’s define static interface as we can define static classes :

    public static interface ICountable

    {

        static int Count { get; }

    }

and implement it on our sample :

    public class Sample4 : ICountable

    {

        private static int count;

        public static int Count { get { return count; } }

 

        private readonly string name;

 

        public Sample4(string name) { this.name = name; }

 

        public void Method()

        {

            count++;

            Console.WriteLine("Total count {0} incremented by {1}", count, name);

        }

    }

The C# compiler would be responsible for creating a singleton stub in the class. Since the goal is to provide a function table, this could also be handled at a lower level by the CLI.

Now, we can have interesting language extensions.

Static member access in generics

Let see it in action :

        public static bool IsInstanciated<T>() where T: ICountable

        {

            return T.Count != 0;

        }

There is no ambiguity when using this method since values of parameter T are known at compilation time. The C# compiler could replace the static call with a interface call on the proxy. On a CLI version, the JIT compiler could resolve it once and for all and emit a static call. Use of a child type whose parent type implements the interface should not be allowed, the compiler could report this.

This could be combined with an extension method syntax to provide extension methods on types :

        public static bool IsInstanciated(static ICountable type)

        {

            return type.Count != 0;

        }

This one is a bit twisted, and I would gracefully admit changes in the syntax, but the point is that it would enable on type/classes the same kind of thing that Linq offers with interfaces : put the minimum set of methods in interface, then add lots of features around interface with extension methods.

Back to reality

Ok, I should sleep at night, but who knows, it’s perhaps useful.

If anyone sees other applications… just drop a comment.

Friday, July 24, 2009

DDD and Code ReUse

I read several discussions against Code ReUse and layered architectures recently :recycle-logo

Different kinds of Code ReUse

You can split your code with different concern :

  • Object model extensions
  • Technical Infrastructure
  • Application code

The first two are good candidates for Code ReUse.

By Object model extensions I’m talking about things that make your code writing less tedious at language level or object model level.

Example of such code are :

  • IEnumerable and Enumerable
  • Collections
  • Reflection helpers
  • Dependency Injection framework

By Technical Infrastructure I mean things that make your code run in its environment :

  • Generic Service Host,
  • ORM, Data Layer
  • Format serializers / deserializers
  • Configuration helpers
  • Communication frameworks (WCF, Service Buses)
  • UI frameworks (MVC, WPF)

The last part is Application code, and here, things are really different.

Application Code ReUse

For long I’ve been writing business code in libraries. I began then to notice problems concerning code and data locality.

When you have a single application (process), no problem.

But if two applications need to modify the same entities, the solution would be to use the same library in both applications so that there is no code duplication. It seems good practice but you quickly stumble on several problems – I’m sure you already experienced it :

  • Synchronization : the same data will be accessed in the same db from two application, how do you manage conflicts
  • Deployment : when you fix bugs or add features, you must redeploy every application that has a dependency on the library. It slows down the release cycle and make it more risky, changes have more impact.
  • Code locality : when a problem arises, you have to find which application it comes from.

Let’s examine DDD patterns to see how they fit with reuse :

Services

Let’s start easy. Services are stateless, they should deliver simple action. But to preserve encapsulation the better is to put services as true services in their own process (web service, windows service, service on a service bus..).

This way, synchronization is managed in process, deployment is a breeze, and no problem with code locality – code executes in one place.

Entities

Entities are retrieved through a Repository Service, hence, they should follow the same rules as Services.

This way, the implementation of a repository that access the database is truly an implementation details. Anyone who wants to talk to an entity sends a command to it, a handler service get the entity from the repository, and pass the command to the entity. The configuration to access the database is local the to the process.

Here again, same benefits.

Moreover entities should always have different meanings in different bounded contexts, the should have different implementations, so there is no real reason for reuse.

Value Objects

Value objects are a bit different.

Some object are very specific to a bounded context and don’t need to be reuse outside.

Some other can be a good way to encapsulate some shared concepts. Money is usually a good example, but there can also be concepts more specific to the domain (you will find them as words that come in the Ubiquitous Language of different Bounded Contexts).

They can be shared among different contexts, but rarely between different domains. There are exceptions for very very generic concept like money, but even money often needs to be tweaked a bit for each domain…

 

Service Bus to the rescue

Once each bounded context is split, you need to organize communications between parts. Here comes the Service Bus and Messages, but now, the only shared parts in the application are :

  • Object model extensions (to code faster and cleaner)
  • Technical infrastructure (so that each process is fully equipped, and there’s not much technical fuss in the application code)
  • General use Value Objects (to manipulate domain concepts instead of int and decimal)
  • Messages (to communicate between contexts)

You could also use web services, but it makes the overall structure less fault tolerant, harder to deploy, and more tightly coupled.

Once you’ve decoupled bounded context using messages, the rest is just an internal implementation detail, why would you want to reuse it !

Tuesday, June 23, 2009

Distributed Domain Driven Design and Aggregates

Once again, Gojko Adzic comes with an excellent post : Improving performance and scalability with DDD.

Aggregates are often a bit underused in DDD because they’re difficult to grasp. They’re often seen as a solution to a technical problem. Gojko shows here how to understand them at a domain level. This post gives a clear vision of the role of Aggregates in DDD by placing it in the context of distributed environments.

You should read it !

Where are my Entities and my Repositories ?

During Evans’ talk at ParisJug, some attendees where surprised that there was no mention of Entities or Repositories

Quite a lot of people where introduced to Domain Driven Design by these aspects and see these as the main advance of DDD.

In contrast, Eric Evans explained to me he had some regrets he placed these patterns so early in the book. Many readers think they know the most important at this point and stop reading after chapter 6.

Actually those patterns are only object model patterns that enable Separation of Concerns and Persistence Ignorance, but can also be used in context that are not Domain Driven at all like CRUD.

Of course, if you want to implement a domain independent of all infrastructure concerns, good OO practices will be required, but those practices won’t make your application Domain Driven (don’t understand that not following DDD would make your design a bad design… you apply DDD if you want and if you need to, but achieving persistence ignorance won’t mean you practice DDD.)

But you’ve more to learn from Strategic Design, Bounded Contexts and distillation of the Core Domain etc.

Friday, June 19, 2009

Strategic Design at DDD Exchange

Gojko Adzik has a post about Eric Evans’ talk at DDD Exchange :

Why do efforts to replace legacy system fail ?

You can also read my previous post about strategic design.

I’m currently working on evolving a large legacy system, and my experience tell me it’s the right way to deal with it !

Don’t try to switch off legacy system. Go along with it using anticorruption layers to protect you elegant core domain.

Wednesday, June 17, 2009

Which model is best ? Thats not the question.

Mercator_1569Those who already read the book should already know this. It’s still interesting for newcomers and you can  send comments if you want !

During his Talk at ParisJug, Eric Evans presented two possible models for Cargo itinerary.

The first one was around the notion of Stops (at a Stop, you unload, then you load), and the second one was around the notion of Legs(you load at the start of a Leg, and unload at the end). An itinerary could be seen as a list of stops or a list of legs.

The question was, which model is best ?

Of course, there is no answer to this question.

The same question was translated to a comparison of maps. First an map of China from the 16th century, and a Mercator projection map.

We should be inclined to say that the second one is best. But the first one was largely enough for the need at that time. And if you inspect the Mercator projection, you can notice that it is not that accurate for some tasks. For example, the Greenland seems abnormally large.

Why do we use Mercator projection then ?

It became the standard map projection for nautical purposes because of its ability to represent lines of constant course, known as rhumb lines or loxodromes, as straight segments.

If you want a map to compare country areas, use a Gall-Petters projection or a  Goode homolosine projection

So the question becomes :

Which model is more useful ?

And for the question to be complete :

Which model is more useful for what ?

To come back to the cargo application, Stops will be useful to produce orders to unload and reload containers from cargos, but legs will be useful if you need to track transport location or change routing during transport.

You’ll have noticed :

It depends on the context

When DDD should be considered ?

This is a recurring question on the DDD yahoo group. And there was a simple explanation during the ParisJug talk.

DDD is not a silver bullet for all application development, it just helps to manage complexity when the complexity comes from the domain.

No need for DDD when working on a technical application or a small application with few interactions.

You could benefit from DDD when your application looks like the Cargo sample :

  • Route containers based on transports availability
  • Take cost and time into account
  • Know where are the boats
  • Organize loads and unloads
  • Manage container storage (emit order of missions for employees on site)
  • Provide container tracking and tracing to clients
  • Transports can be late, manage it
  • Transports can be canceled, manage it
  • Contracts can be changed, destination can change
  • Containers can be incorrectly routed even if emitted orders where correct, manage it.
  • Manage taxes
  • Manage time zones
  • Manage currencies
  • Manager constraints and local rules on dangerous containers contents

In this kind of application, the complexity doesn’t come from an Xml web service or a database schema. Even without taking account any technical concern, it is complex !

So there is a simple rule of thumb to know if DDD could apply (independently from the size of the project) :

Try DDD if Domain Complexity >> Technical Complexity

In other case you can just go with your preferred classic architecture.

Tuesday, June 16, 2009

Met Eric Evans at ParisJug

IMAG0387 The ParisJug organized a DDD event yesterday in  Paris presented by Eric Evans, the author of Domain  Driven Design himself.

He’d come in France ten years ago, but never made a presentation about Domain Driven Design here yet.

Thanks to Antonio and Nicolas and the others and who organized this presentation in 4 days. You can find a summary of the talk in French here.

Putting the model to work

It was the title of the talk. I’ll not make a full report since it was mainly what’s in the book for those who had not grasped the concepts of DDD yet.

I’ll talk about important topics of the content in following posts.

Diner with Eric Evans and Jug guys

After the presentation, we moved to a restaurant with Eric Evans, the organizers and other attendees. I had the chance to be at the same table as Eric, so I had the opportunity to talk with him about a lot of things.

He’s not at all the Pattern Guru kind. Very careful to let you understand he’s not found a solution to your problems, that you’ll have to work, but that his experience and analysis can help to grasp things a bit more clearly. He’s constantly working hard on several project to get more experience and set his knowledge and experimentation against different contexts.

I’ll also talk about part of our discussion in following posts.

Tuesday, May 19, 2009

IOC Container, Go Hide (part 2)

Ok, there seem to be some misunderstanding with the suggestion from my previous post.

A framework manipulates two kind of objects :

  • its objects
  • your objects

You don’t care about its object, you care about yours.

So you want to be able to take part in your objects instantiation so that you can do your own stuff (inject dependencies, handle differently based on runtime behavior…).

Without container

Look at Asp.net, when it needs to create an Http Handler, it calls a IHttpHandlerFactory.

You can provide your own IHttpHandlerFactory, just implement its two methods (the second one can even be left empty in most cases) :

public interface IHttpHandlerFactory
{
// Methods
IHttpHandler GetHandler(HttpContext context, string requestType, string url, string pathTranslated);
void ReleaseHandler(IHttpHandler handler);
}

In the GetHandler method, you’re free to use the container you want ! But you can also do this :

return new CustomHttpHandler(theDependency);

Or make a call to another factory, or… or…

With container

The framework ask to provide a container so that the it can simply run. Ok there is also a builtin container so I don’t have to care.

But if I want to do a custom instantiation I have now to implement the following interface :

public interface IServiceLocator : IServiceProvider
{
// Methods
IEnumerable<TService> GetAllInstances<TService>();
IEnumerable<object> GetAllInstances(Type serviceType);
TService GetInstance<TService>();
TService GetInstance<TService>(string key);
object GetInstance(Type serviceType);
object GetInstance(Type serviceType, string key);
}

This interface will be used when any instantiation will occur. If I mess internal framework instantiation. Wooch !

And there is no clear meaning with this interface. It should be able to instantiate any object requested.

It doesn’t give a clean and clear API in my personal opinion !

Using an IOC container as an extension point is clearly an over abstraction !

Provide clear, focused extensibility points

The framework doesn’t need to be extended on every instantiation, especially when instantiation its own internal stuff. There are clear extension points, and a specific interface should be created for each.

This is just a framework design good practice.

Then, there is no need to show the container you use to the outside, and it resolves potential version conflicts.

Friday, May 15, 2009

IOC Container, Go Hide !

558287_49024807While testing NServiceBus and MassTransit – yes I need a service bus framework for my current project – I’ve seen that both library where relying on an IOC container, in two different ways.

Warning: This article is not to flame these two frameworks that seems of great quality. There are still few guidance on using IOC containers in libraries. This is the topic of this post.

The NServiceBus way

NServiceBus relies on Spring or Castle Windsor.

You can notice it when instantiating the Bus :


var bus = NServiceBus.Configure.With()
                .SpringBuilder() // or .CastleWindsorBuilder()
                .MsmqSubscriptionStorage()
                .XmlSerializer()
                .MsmqTransport()
                    .IsTransactional(true)
                    .PurgeOnStartup(false)
                .UnicastBus()
                    .ImpersonateSender(false)
                .CreateBus()
                .Start();

And when looking at the library with Reflector :

image

and

image

Yes, the Spring framework and the Castle.Windsor are ILMerged in the NServiceBus assembly.

NServiceBus abstracts the container with the NServiceBus.ObjectBuilder.IBuilder interface :

public interface IBuilder
{
    // Methods
    T Build<T>();
    object Build(Type typeToBuild);
    IEnumerable<T> BuildAll<T>();
    IEnumerable<object> BuildAll(Type typeToBuild);
    void BuildAndDispatch(Type typeToBuild, Action<object> action);
}

 

The MassTransit way

MassTransit adopts a slightly different strategy.

The base is still the same.

It uses the CommonServiceLocator to have a ‘standard’ interface to hide the actual IOC container implementation.

It provides implementations for the most common IOC frameworks (Castle.Windsor, NInject, StructureMap and Unity – but it doesn’t work so well…) through additional dlls.

The big difference is in the library configuration. You configure the container (through code or configuration). Then encapsulate the container in a Common Service Locator implementation that acts as an adapter. Finally give it to the library.

 

What’s the problem

In both case, the intent is good, but hell is paved with good intentions.

In Mass Transit, the design is clearly made so that you can choose your container and integrate the library seamlessly with it. You can manage the configuration in your container the way you do it in your application.

But wait ! What if I don’t need an IOC container in my application ?

The other problem is that Mass Transit relies on some advanced IOC capabilities like contextual configuration. The object instantiated for IEndPoint should not be the same depending on the parent object. This scenario is not handled by Unity for instance.

Maybe Unity is not good enough, but how can I know which other specific feature Mass Transit relies on ? No clue.

And providing a library configuration through a container doesn’t seem a best practice to me. The API gives no clues of what I should provide to the library in order to run it.

The only way to know is to launch it, see where it throws an unresolved dependency exception, add the dependency and retry !

And I’ll probably never know about optional dependencies.

On the other side, NServiceBus works with a NServiceBus specific configuration (code and app.config) that indicates  clearly what I must provide to the library.

But Jak Charlton had a serious problem with NServiceBus. He’s not using the same version of Castle.Windsor that the one merged in the NSB assembly ! And the assembly load fails.

 

What’s the solution then ?

I clearly prefer the specific configuration scheme of NServiceBus, but how can we solve the version problem ?

I will answer with another question :

Why does NServiceBus need two IOC container implementations ?

For library creators, I will propose this way to go :

  • Choose the container that provides the features you need
  • Use it in your infrastructure
  • Create a clear configuration model that exposes the required and optional dependencies that should be provided by the library user
  • Consider creating a app.config specific configuration (there are good tools in the framework for that)
  • ILMerge your container framework as internal in your assembly.

The alternative to ILMerge is to fork your framework (if it’s open source) and put it as internal directly in your code.

The advantages

  • No conflict with potential other versions of the container framework
  • A clear discoverable configuration
  • No need to use a IOC container to use the library.

What if the container needs to inject dependencies in the user objects ?

Both NServiceBus and MassTransit instantiate user’s objects on the fly.

How can the user add it’s own dependencies if he has no access to the container ?

Let’s step back a little and consider what we would do if there was no container…

  • We would use Activator.CreateInstance to create the object.
  • Then we would consider it would not let the library user enough options, so we would propose a hook so that the user can manage the instantiation himself. It could be a callback or an interface.

When instantiating user objects with the internal framework IOC container, you remove to your users the right to manage the instantiation themselves.

So come back to this good practice. If the user wants to use a IOC container to instantiate his objects with dependencies, let him do this his own way. And his container will not be loaded with all the framework internal dependencies, this will avoid other conflicts.

Conclusion

Hide your IOC container framework inside your library, it’s a private implementation detail of your framework and we don’t wanna know !

Choose the framework you like, hide it so that it cannot conflict with the one I want to use and we will be friends !

It surely advocates for frameworks with a small footprint, but once again, it’s a private detail.

 

Continued on IOC Container, Go Hide (part 2)

Thursday, May 7, 2009

Decimal, what are those trailing zeros ?

Yesterday, I stumbled on something I didn’t expect at all…

An exception appeared while testing my code that I had been carefully writing following Design By Example..

Looking in my debugger my decimal two variables had value 4M.

But calling ToString on it led to different results : “4” and “4.00”…

What the heck ?! How come ?

 

I should have known this

Yes, the MSDN state it explicitly :

The scaling factor also preserves any trailing zeroes in a Decimal number. Trailing zeroes do not affect the value of a Decimal number in arithmetic or comparison operations. However, trailing zeroes can be revealed by the ToString method if an appropriate format string is applied.

And I did not know that, did you ?

 

Try it yourself

you can try it yourself :

Console.WriteLine(1m);      // 1
Console.WriteLine(1.0m);    // 1.0
Console.WriteLine(1.00m);   // 1.00

Console.WriteLine(1m == 1.0m); // true
Console.WriteLine(1m.ToString() == 1.0m.ToString()); // false

The decimal.Parse function also preserve trailing zeros :

Console.WriteLine(decimal.Parse("1.0", CultureInfo.InvariantCulture)); // 1.0
Console.WriteLine(decimal.Parse("1.000", CultureInfo.InvariantCulture)); // 1.000

 

The explanation

The decimal type internally represents values using an 96 bit integer and a negative power of 10 (between 0 and 28).

Those values are simply internally stored like this :

1.0 –> 10 * 10^-1
1.000 –> 1000 * 10^-3

You can check it using the decimal.GetBits method.

The trailing zeros are even maintained in arithmetical operations :


Console.WriteLine(2.0m * 3.00m);  // 6.000

But are handled correctly by the equality and comparison methods :

Console.WriteLine(1m == 1.0m);  // true
Console.WriteLine(1m.GetHashCode() == 1.0m.GetHashCode()); // true

 

Do you know other secrets like this ?

Of course, my unit tests did not test case I didn’t expect to happen !

But, Hey ! If you knew it, you should have told me before !

What secret feature/behavior in the .Net framework or in the C# language do you know ?

Tuesday, April 28, 2009

Strategic Design

I was looking yesterday at Eric Evans’ talk at the Øredev conference last November.

You really should see it to understand better one of the most important part of the DDD book that is difficult to grasp on first reading.

I’m currently working on a small company that had a problem with scaling their system. The existing system was working correctly but was going to stall in both performance and evolution perspectives.

When we arrived, the plan of the preceding head of development was :

‘We need to restart from scratch, let’s specify everything, then code a clean version 2.0 in two years, and switch the legacy system off.’

Of course it was expected to fail.

And even if it succeeded, after two years, they would have got the same software that two years before.

It could be cleaner, but who cares ?

When you’ve lost two precious evolution years, for a promising startup, count it as dog years.

When we took control of the situation we planned the following :

  • Extract the core business value of the software.
  • Spot where you need new features.
  • Develop new features as if it was in a clean environment.
  • Develop anti corruption layers to hide the legacy system behind clean interfaces.

This way you start to work on new business value now, you make the model cleaner over time, and you have benefits of the working legacy system instantly.

Don’t waste your time recoding what is already working.

Act to add value to your business.This is where your craft should go.

Geek balance... or not !

I moved to my new house recently, and I was working last week end on the new kitchen tiled splashback. Scott Hanselman would say it’s a good way to find geek balance outside my comfort zone

DSC00061

But did I really put aside the geek in me ? Not really if you watch carefully…

Can you find why ?

Soon a picture of the full result…

Saturday, April 18, 2009

TDD becomes Design By Example

Just have a look to Brad Wilson’s post It's Not TDD, It's Design By Example.

What the name Test Driven Development has going against it is that it doesn’t properly express the purpose of TDD; namely, that it is a process designed to help you drive and iterate the design of your implementation at the unit level.

[…]

Frustrated by the misunderstanding of the purpose of TDD, my friends and I (Peter, Jim, Brian, Scott, and many others, all agile practitioners and coaches) decided to start calling it Test Driven Design. A small change, but it starts to focus on the fact that the process is about design. Unfortunately, that “test” word baggage is still in there, so our next iteration was then Example Driven Design. This worked well too, but “EDD” and “TDD” were still too close together and confusing.

The final iteration ended up being Design By Example (DbE). Now when I talk about TDD, I always call it Design By Example, and explain why we like this name better than TDD. Where TDD(esign) or EDD failed to get traction, people really seem to resonate to Design By Example.

I think we can all gain clarity by using Design by Example instead on TDD. I adopt it from now on.

We still have to find disambiguation for highly overloaded terms like Service and Repository… 

Wednesday, April 8, 2009

Back on Repositories and Paging. Introducing reporting.

I had quite a lot of comments on my previous post on repositories and paging, and there’s a lot of people coming from google looking for answers… It’s sign that there’s no good response to this issue now.

The problem was how paging (a presentation concern) fits into a repository that should have only domain concerns…

And the short answers is… It doesn’t fit !

It doesn’t mean you should forget everything I told you before but there’s a vision change.

There’s something missing in DDD book…

but present in current discussion about DDD. The book provides good building blocks (entities, repository…) but Evans says himself it has been a bit over emphasized. The book is mainly about maintaining and mutating your domain state, not about it’s presentation.

CQS to the rescue

The CQS (Command Query Separation) principle proposes to decouple Commands that change the state of the system, from Queries that ask the state of the system.

The repository lies on the Command side, that’s why :

  • It should be specialized to express only mutations that are possible for the system
  • It should not expose presentation concerns like paging

But what’s on the Query side ?

The query side should be far more supple and provide tools to query the state of the domain. It can even be implemented with IQueryable interfaces to provide that flexibility. Asking for pages in this area is natural since you just want to query a part of the domain state.

The goal of all this is to report the state of the system. So Reporting is a good name here.

You can read Greg Young’s DDDD posts to see where CQS can lead : Write only domain model (Commands) and rich scalable distributed Query mechanisms using messaging.

There’s no clear guidance yet in this field but I’m still investigating. The flexibility of a reporting service in the domain layer is still a huge gain to understand where each concept fits.

Thursday, March 12, 2009

QCon London 2009

Today, there's a full QCon London track dedicated to Domain Driven Design.

Eric Evans exposed this morning what he's learned about DDD since the book, and lots of interesting things.

Gojko Adzic posted a report of Evans' talk.

The whole slides should be available on QCon site shortly.

You can also follow in on twitter through Richard Banks reports.

 

Wednesday, March 4, 2009

How *not* to inject services in entities

syringeI’ve seen lot of people asking where and how to inject services in entities. The services in question are often repositories by the way…

The response is simple :

 - DO NOT inject services in entities !

- Ok I see, you’re against dependency injection

- NO, I'm not against dependency injection, I use it a lot.

- You can still use a static service locator…

- I avoid service locator when I can, especially when the service locator must be static…

– So you’ll get an anemic object model !

- I don’t think so.

 

Injecting services in entities is wrong

You’ll find me a bit presumptuous, but I say it again : Injecting services in entities is wrong.

Nesting objects is not a problem from an OO point of view, but we’re talking about a special kind of objects, entities.

 

Entities are all about their state management, and this state management can require several objects.

  • Code infrastructure objects like lists or dictionary to handle collection of data,
  • Object oriented constructs to leverage code maintenance techniques like strategies.

Entities don’t have to be classes with public setters and getters… you should even avoid this to keep you entities in a consistent state.

But there is no reason for an entity to keep a reference on a service, since it’s not part of its state.

There are usually three situations in which people thinks they need it :

  • Lazy loads
  • Relations
  • Behavior methods

Let’s review each point…

 

Lazy loads

Sometimes, an entity property is heavy to load and is not required by all code paths. In this case, loading it upfront can lead to performance problems.

The usual way to work it out is to hold a reference to a data access object or a repository and to load and cache the requested data on demand.

 

 Using a data access layer object in the entity is clearly a break of persistence ignorance, but using a repository is not a better option.

 

The repository is a way to abstract persistence in the model, but it’s still a persistence concern even if modeled in terms of domain terms.

I’ve already posted about ways to solve this problem in Lazy load and persistence ignorance and part 2.

 

Relations

I was twitting yesterday with Kyle Baley about the need to have an Event repository in the Users entity. He wanted to get the User Team for the current event. I think you don’t need more context to understand the problem.

The User did not know about the current event so it needed the Event repository to find it and find the corresponding team.

But why does the User entity expose a CurrentTeam property if it doesn’t know about Events ? There’s something missing here.

The whole picture becomes clearer if you add a Participant entity that embodies the participation of a user to an Event, and no repository is needed anymore since you don’t need a CurrentTeam property on User.

 Make relations clear instead of hiding it in repositories.

 

Behavior methods

If I have mail message entity and I want a Send method on it ?

Tiding your entity to the service that will use it is not conceptually satisfying. The server that will send the message is a medium and is not part of the entity itself.

It’s seems better to call server.Send(message).

The problem is that you can end breaking the tell don’t ask principle because the Send method will ask the message for each property value. And you can be tempted to put computations that should be in the message entity inside the Send method.

 

Let’s call Double Dispatch to the rescue !

  • Design a server interface presenting a Send method that take the parameters it need (title, recipients, message body…)
  • Add a SendThrough method to your entity that takes the server interface as parameter
  • Implement SendTrhough so that it computes values to pass to the Send method
  • That’s it.

 

Here is a small sample implementation :

    public interface IMailService

    {

        void Send(string sender, string recipient, string subject, string body);

    }

 

    public class Message

    {

        //...

        public void SendThrough(IMailService mailService)

        {

            string subject = isReply ? "Re : " + title : title;

            mailService.Send(sender, recipient, subject, GetMessageBody(content));

        }

    }

The entity is not tied to the service before needed. So no need for injection.

 

Is injection useless ?

There is no problem to inject services with other services, and it’s even easier since services have no state, they only need their dependencies in constructor, and to my opinion it’s the cleanest injection mode.

Usually domain services will need infrastructure services dependencies, and in this case a dependency injection framework can make things easier.

Following the preceding advice, you’ll never need to use your dependency injection framework as a service locator, and you’ll never have to perform buildups on your entities, and you’ll feel much better.

 

What’s your way to deal with it ?

For now I’ve always find a way to get rid of services inside entities, but I really would like to hear cases where you’re stuck with it to see if another way is possible, or cases where you think there is really a good reason to go this way.

Tuesday, February 24, 2009

Domain Driven Design Step By Step

Casey Charlton is moving his DDD series on a wiki site so that every body can put it’s personal touch.

You can find it and participate at : http://dddstepbystep.com/

Expect me to write there !

- page 2 of 4 -