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.
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.
I think that nobody have done that kind of comparison and if it had been, then it wouldn't be small. Domain Driven Design tries to solve complexity and a simple example doesn't contain complexity.
Maybe Domain Driven design Step by Step will give you some answers.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With