adam bien's blog

Different Persistence Styles - and there is no single truth 📎

My last post about rich domain objects caused some traffic in the comments area. It seems like the whole idea of rich, persistent domain objects is controversial. Especially the getters/setters are discussed a lot. In my opinion there is no single truth. Rich Domain Objects (e.g. PDOs from p4j5) are suitable in case:
  1. You need inheritance and polymorphism (e.g. special computation in concrete classes)
  2. The behavior can be state dependent.
  3. A method call can change the state of not only one object, but whole object graph (or tree).
  4. Shortly: when object orientation is needed :-)
On the other hand, in every application there is some "throw-away" code like master-data management, infrastructure and admin stuff etc. for this cases persistent anemic objects (PAOs from p4j5) are superb. They mainly consist of accessors, do not have any business logic (perhaps some simple validation) and can be well generated. There could (and in general are) be some core components built with PDOs, others with PAOs in the same application. From my perspective PAOs have the "touch" of throw-away code. The development of PDOs is more time consuming, but PDOs are also more powerful and easier to maintain. As Jason Carreira mentioned the separation of the core-logic of a PDO and the cross-cutting concerns is the key to success.
The real world is even more complicated. Sometimes neither PDO, nor PAOs can be used, and dataset oriented styles are more appropriate. Especially stored procedures are not directly supported by JPA, so Integration Services (like DAOs, see Integration Service from p4j5) have to be realized to access the stored procedures and map the results.
But also from the business perspective the object-relational mapping is not always the way to go. Especially reports, imports, exports can be often much easier realized with dataset, than oriented persistence.
...we just have to use the right tool for the job