Sunday, August 15, 2010

From layers to hexagonal architecture

The traditional layered architecture consists of data, domain and presentation layers.

Separating the presentation layer from the domain layer is rather easy. The presentation layer objects query the domain for data to display on the screen. The persistence layer is another story. The fact that it appears below the domain layer prohibits any of the classes in it knowing about the domain entities.

But consider a Fetcher class for example, a class that has responsibility for querying some domain object from the database. It has the domain type in the signature and thus has to be defined in or above the domain layer. This is leaking of the data access object out of the persistence layer.

This problem has been recognized and here we have an architecture which works around it by separating out the domain objects package. But the result is not as clear and compelling as the layered architecture.

The civilisation progressed and an architecture with nothing below the domain model has been discovered. One can see this in the ddd sample.

The persistence concern is implemented as part of the infrastructure layer. Infrastructure is that vertical layer that depends on the three other layers. Domain knows nothing about the infrastructure.

Another example is the Hexagonal Architecture.

The domain sits in the core of the application, with the persistence aspect implemented by an adapter. The adapter layer corresponds to the infrastructure and the interfaces layer combined from the ddd sample architecture diagram. The important part is that the domain does not depend on anything else.

Such layering is achieved by defining service interfaces in the domain layer for persistence purposes. These abstract interfaces are implemented by the adapters in the outer layer of the application and injected into the objects that need them.

As a result nothing in the domain layer needs to import anything from the hibernate package, or whatever persistence technology is being used. The domain layer has a custom made, abstract interface to persistence service, in its own terms. The domain code can be expressed without the details of the persistence technology being used.

No comments: