Sunday, March 6, 2005

A couple of views on coupling

Having read both Domain Driven Design and Hibernate in Action recently, I found an interesting contradiction between them...here's what Eric Evans has to say about promiscuous coupling between your domain classes:

"It is important to constrain relationships as much as possible. A bidirectional association means that both objects can be understood only together. When application requirements do not call for traversal in both directions, adding a traversal direction reduces interdependence and simplifies the design. Understanding the domain may reveal a natural directional bias."

...and here's what Gavin King and Christian Bauer have to say on the same subject:

"Good uses for unidirectional one-to-many associations are uncommon in practice, and we don�t
have one in our auction application. You may remember that we started with the
Item and Bid mapping in chapter 3, making it first unidirectional, but we quickly
introduced the other side of the mapping."

So I agree with Eric, but I'm using Hibernate. Things that make you go hmmmm....

3 comments:

  1. There's no reason why both ends of the relationship need to be visible to the rest of the app, so just use "field" level access and your domain model will have minimal cruft added to it.

    ReplyDelete
  2. This is one of the places where I think that Evans got it really wrong. In the domain layer, bidirectional associations should be the norm. If you want to find out what school Johnny attends, you shouldn't have to search every school to see if Johnny is a student there. Just ask Johnny which school he goes to.
    This also makes it easy to be sure that Johnny is only enrolled in one school at a time... a common type of business rule that is non-trivial with unidirectional associations.
    The "understand separately" argument is pretty weak for domain classes. You can't really understand what a school is without understanding what a student is, nor can you understand what a student is without understanding what a school is.
    In the application layer, though, bidirectional associations will be rare.

    ReplyDelete
  3. The difficulty with bi-directionality is in keeping the relationship links consistent. I don't know about Hibernate (maybe it enforces consistency) but for POJOs this isn't easy. For example, what happens when an exception is thrown after setting one of the links but not the other?

    ReplyDelete