Sunday, December 18, 2005

Spring 2.0 vs. the Anemic Domain Model

Spring 2.0 vs. the Anemic Domain Model

One of the most interesting aspects (no pun intended) of Spring 2.0 that was discussed this past week at The Spring Experience was the idea of letting Spring configure beans post-instantiation and regardless of how the bean became instantiated. This Spring 2.0 feature helps avoid the Anemic Domain Model" anti-pattern as described by Martin Fowler.

It's very common in Spring to build applications where service objects are injected with DAO objects and use those DAO objects to handle persistence of domain objects. The domain objects themselves, however, are little more than dumb data holders. The problem with this approach is that the interaction between the service object and the DAO object is very procedural. The service object makes one or more calls to the DAO, passing the domain object around like cargo.

Ideally, the domain object would contain behavior to handle its own persistence. If domain objects offered such behavior, then the service object could deal directly with the domain object in a very object-oriented way. Instead of telling a DAO to persist a customer, the service would tell the customer to persist itself. There will still be a DAO, but the domain object will do its own dealing with the DAO, unbeknownst to the service object. In effect, the domain object and the DAO swap positions with relation to the service object.

If the domain object is responsible for dealing with the DAO, then the domain object must have access to the DAO. In Spring, we'd like to do this through dependency injection. But domain objects are typically instantiated outside of Spring (e.g. in Hibernate, iBATIS, or some other persistence mechanism). How can Spring inject a DAO into a domain object when Spring isn't the one instantiating that domain object?

Full article..
http://jroller.com/page/habuma?entry=spring_2_0_vs_the

No comments:

Post a Comment