By its very definition, the foundation of a conventional layered architecture is the database. The web layer depends on the domain layer, which in turn depends on the persistence layer and thus the database. Everything builds on top of the persistence layer. This is problematic for several reasons.
Let’s take a step back and think about what we’re trying to achieve with almost any application we’re building. We’re typically trying to create a model of the rules or “policies” that govern the business in order to make it easier for the users to interact with them.
We’re primarily trying to model behavior, not the state. Yes, the state is an important part of any application, but the behavior is what changes the state and thus drives the business!
So, why are we making the database the foundation of our architecture and not the domain logic?
Think back to the last use cases you implemented in any application. Did you start by implementing the domain logic or the persistence layer? Most likely, you thought about what the database structure would look like and only then moved on to implementing the domain logic on top of it.
This makes sense in a conventional layered architecture since we’re going with the natural flow of dependencies. But it makes absolutely no sense from a business point of view! We should build the domain logic before building anything else! We want to find out whether we have understood the business rules correctly. And only once we know we’re building the right domain logic should we move on to build a persistence and web layer around it.
A driving force in such a database-centric architecture is the use of object-relational mapping (ORM) frameworks. Don’t get me wrong, I love those frameworks and work with them regularly. But if we combine an ORM framework with a layered architecture, we’re easily tempted to mix business rules with persistence aspects.
Figure 2.2 – Using the database entities in the domain layer leads to strong coupling with the persistence layer
Usually, we have ORM-managed entities as part of the persistence layer, as shown in Figure 2.2. Since a layer may access the layers below it, the domain layer is allowed to access those entities. And if it’s allowed to use them, it will use them at some point.
This creates a strong coupling between the domain layer and the persistence layer. Our business services use the persistence model as their business model and have to deal not only with the domain logic but also with eager versus lazy loading, database transactions, flushing caches, and similar housekeeping tasks.
The persistence code is virtually fused into the domain code and thus it’s hard to change one without the other. That’s the opposite of being flexible and keeping options open, which should be the goal of our architecture.