Is there a rich domain model example?

Dónal picture Dónal · Nov 2, 2009 · Viewed 9.1k times · Source

I'm looking for a simple example to illustrate the benefits of using a rich domain model. Ideally, I'd like a before and after code listing (which should be as short as possible).

The before code listing should show the problem being solved using an anemic domain model, and a lot of fairly procedural service-layer code, and the after code listing should show the same problem being solved using a rich, object-oriented domain model.

Ideally the code listing should be in Java or Groovy, but anything fairly similar (e.g. C#) would do.

Answer

Miguel Ping picture Miguel Ping · Nov 17, 2009

I'll give you a simple example of real production code:

Person.groovy:

  List addToGroup(Group group) {
    Membership.link(this, group)
    return groups()
  }

Membership.groovy:

 static Membership link(person, group) {
    def m = Membership.findByPersonAndGroup(person, group)
    if (!m) {
        m = new Membership()
        person?.addToMemberships(m)
        group?.addToMemberships(m)
        m.save()
    }
    return m
}

Whenever I want to bind a person to a group, I can just do person.addToGroup(group)

The procedural code would be something like this, on your controller:

def m = Membership.findByPersonAndGroup(person, group)
 if (!m) {
        m = new Membership()
        person?.addToMemberships(m)
        group?.addToMemberships(m)
        m.save()
}

At first sight, you can say that you can wrap that in a function and you are good to go. But the advantage of rich domain design IMHO is that it is closer with the way you think, thus closer to rationalize on. In this particular example, I just want to add a person to a group, and the code will read just that.

This is a short example like you asked, but it's easy to expand this example and see that you can build complex interactions with proper domain modeling.

You can also see Martin Fowler's Transaction Script vs Domain Model for a brief explanation of these two patterns, which I consider related to DDD.