"onion architecture compared to hexagonal" Code Answer


what are the differences between them if any?

onion: there are layers, with the dependencies always pointing inwards, i.e., a layer can use any of the layers inside it. the inner layer is domain model and the outer is infrastructure, but the number of layers between may vary.

hexagonal (it's an alternative name for the original name "ports & adapters"): there are no layers. you have the application, the ports, and the adapters. the ports belong to the application, they are the api/spi of the application. adapters are outside the application, and each one depends on a port of the application.

the confusion some people have is that when implementing the hexagonal architecture, most of the people don't physically put every adapter in an artifact, but they put all together into one artifact (like the infrastructure layer). and also they make depend on the adapters on the whole app, not just the port they use. so it would be an onion in fact.

implementing hexagonal right should separate adapters from each other, and every adapter should depend just on the port it uses/implements (depending on whether the port is a driver or driven).

another difference is that hexagonal says nothing about the structure of the inside of the hexagon (the application).

what are the benefits of using one over the other?

the benefit of hexagonal is that it is more modular, you have a clear separation of components, preventing the leaking of code between them. onion, on the other hand, is more dangerous in that sense, as you can access for example the database directly from the ui (they both belong to the same layer).

the benefit of onion is derived from the above. as hexagonal have a lot of artifacts, if the project is big, the build of the whole project should take a lot of time.

why you would use it? when to use it?

the point of using either of them is that you focus on the real problem you are trying to solve, without using any technology or framework. the application is technology agnostic, and it is easy to migrate from a framework to another. both of them are called "clean" architectures because of that. you have your application core free of framework code, annotations, etc.

so... why use them?

because you improve maintainability, testability, and you have clean code.

when to use them?

i should rather say when not to use them. if the app you are developing is not complex, for example, it's just a crud, maybe it doesn't deserve to use them.

personally, i like "ports and adapters" over the others.

hope my explanation helped.

By jparimaa on January 30 2022

Answers related to “onion architecture compared to hexagonal”

Only authorized users can answer the Search term. Please sign in first, or register a free account.