Tuesday, May 1, 2007

Anemic vs. Rich Domain Models

There's debate at almost religious intensity on some forums as to the type of domain model to be used in developing applications.

The rich Domain Model (proposed by Martin Fowler) suggests having e.g. Employee objects, with all operations on an Employee provided by the class itself - such as Employee.Save(). Fowler argues that this makes for better object orientation, as there is greater encapsulation and the opportunity for polymorphic use of objects.

The alternative is the Anemic Domain Model (the term coined by Fowler himself makes clear how much he dislikes the model by using a term with negative implications) and probably inspired by the design of stateless session beans from EJB. This design has (to follow the above example) Employee objects containing their own data, but EmployeeManager or EmployeeService classes containing the operations - such as EmployeeManager.Save(Employee).

Wikipedia labels the latter as an anti-pattern; however, given that there are so many proponents of the Anemic Domain Model (ADM), labeling it an anti-pattern seems to be an extremist, dogmatic point of view. The pro-ADM argument is that breaking the functionality out into separate classes further enhances separation of concerns, which is a good design practice.

Personally, I've found the ADM to be a simple one to develop, lending itself well to generation of code via templates etc. Furthermore, with the whole SOA/Web Service buzz, services as per ADM make a lot of sense; even use of the GOF Facade design pattern would probably lead to the same solution. Say in a Web Service application, the designer would be forced to make the Domain Model dependent on the relevant Web Service - in my book, placing Web Service calls behind Employee.Save() would be mixing up far too many concerns (i.e. business logic + web service invocation code).

Fowler's rich Domain Model is an ideal solution - and I've used it successfully on several in-process solutions - and if it can be achieved outside of the pro-ADM arguments just outlined - I'm all for it. Maybe having the UI talk to a rich Domain Model (your formal API), which in turn talks to the back end comprising an ADM would be the answer... however, this would mean code that would be repetitive and leave that much more room for defects to creep in.

It all comes down to a question of how pragmatic a software designer is willing to be. The only certainty is that this argument will not be going away anytime soon.

A few blogs which have opinions on this topic:
Finding references on this matter is not hard at all...
Google for rich Domain Model
Google for Anemic Domain Model