Which is better practice in web development, an anemic domain model or rich domain model?
Anemic domain model means entities are dumb POJOs mapped to some persitent storage. Getters and setters doesn't validate the state transition, but trust the layer above. It's the responsibility of service layer to validate the legal state of the entity, and emit an error if the business rules are violated. This is how I'm used to build web application with Spring and Hibernate.
Rich domain model means validation logic (business rules) resides in the entities itself, such as exception is thrown from a setter, if illegal state transition is attempted.
After giving a deeper insight, rich domain model is closer to OOP principles, where as anemic domain model is as procedural as passing a struct to C function (in fact, setters and getters are just a boilerplate here, in a honor to javabean contract). Then why anemic domain model is more adopted, what are the pros and cons of both approaches?
I could see some problems with a rich domain model. For example, if and when the valid state of entity depends of the state of some other entities, but entity doesn't have the reference to all of them, how could we validate the state from within the entity? We could access the database from setter, but this would leak the persistence mechanism to business logic, a very bad design indeed. Also, unnecessary validation would be performed when ORM loads an already validated object from a database and sets it's values! With business logic residing in the service layer, it's much easier to add ad hoc validation logic as the requirements changes, and keep domain model clean of infrastructure code. Actually in the either case business logic IS tied with the persistence, and in practice domain models are worthless without the logic, but when the logic resides in services, we could apply different set of rules to same entities in different context. Am I right thinking this is the purpose of service layer?
Also, hibernate or other persistence mechanism expects entities are POJOs and are interested just getting and setting the values. Of course, with rich domain model database should always be in consistent state, but what would happen if it wasn't? What impact rich domain model would have with modern ORM frameworks?
I asked this question as I recently read that anemic domain model is an anti pattern. I got confused and want to hear some justify for such a statement.