DDD Could Have Saved The Day

"[email protected] [domaindrivendesign]" <[email protected]> 14 Jul 2015 18:59:30 -0700
Newsgroups gmane.comp.programming.domain-driven-design
Message-ID <[email protected]>
Recently, I was reminded of one of the reasons I love DDD.

I recently encountered a production problem that, it turns out, could have been avoided if one particular DDD pattern had been followed:Never create an entity in an inconsistent state.  By adhering to this, it becomes syntactically impossible to encounter an invalid entity.

In this case, there was an entity that could be created in an invalid state: Settings.  A Settings has a TaskDefinition child entity.  The schema correctly enforced a NOT NULL FK constraint for the child entity; however, the Settings constructor did not accept nor instantiate its own TaskDefinition.

The code that broke looked something like this:

1. var settings = new Settings(...)
2. // do some other stuff
3. settings.TaskDefinition = new TaskDefinition(...)
4. Commit

This is a .NET system using NHibernate.  This code happened to work in local and QA testing, but broke in production.  The production system had additional data and configurations that drove the complex logic behind step 2 to do quite a bit more than it had in the local or QA tests.  This extra work filled up NHibernate's buffer to the point that it decided to automatically flush it, including the invalid Settings object, before step 3.  The outcome: a SqlException ruining my morning.

The code was fixable with a little refactoring; however, I wish it hadn't gotten that far.  If our no invalid entities DDD guideline had been adhered to, it wouldn't have gotten that far.