6 ms·
Why Use Onion Layering?
- theamk 2y agoReads like a middle part of the post... What exactly does author mean by "onion layering" and what are they being opposed to? The author supplies some examples (new API field, new microservice dependency, new library dependency) but their fixes seem to apply to any well-organized code - I don't see why you'd need to use some mysterious "onion layering" to create a wrapper around insane dependency and isolate it from the rest of the code. (Google searches show only a few results and they all seem slightly different, so I am guessing this variant of "onion layering" is something author made up but didn't share with anyone - their blog has only one post)
- garrettdbates 2y agoThank you for the feedback on the lack of context. Added some preamble and related background articles.
- 8note 2y agoI think you're looking for https://jeffreypalermo.com/2008/07/the-onion-architecture-part-1/ https://jeffreypalermo.com/2008/07/the-onion-architecture-pa...
- theamk 2y agoExcept your link has layers as "(Infra / UI / Tests) -> application -> domain services -> domain model", with "core" cross-cutting via inner 3 layers While OP has "config -> (API / Infra) -> core" Seems pretty different... I don't think author was referring to that particular page.
- cjohnson318 2y agoYeah, I was confused. This is basically just, "have well defined interfaces, and pass simple data through them", but with no concrete examples.
- DrMiaow 2y agoIsn't this how everyone (competent) designs systems?
- efnx 2y agoYou would hope, but some folks don’t have a background in APIs and don’t really know when life could be better.
- barbariangrunge 2y agoWhat do you mean by background in apis? You mean experience working with them?
- efnx 2y agoI mean designing APIs. Working with APIs is a different discipline than designing them and it takes practice to get it right.
- Sankozi 2y agoNo, you do not need to design system like that. Just because there is a chance that something might change (domain logic, library/REST API), does not mean you need to create anti corruption layers everywhere. They limit problems during the (possible but not certain) change but they make code less readable, less performant and harder to test. Always analyze and decide if it is worth it.
- whstl 2y agoI feel like systems design is a bit like the Anna Karenina quote, every good software is alike, but the bad ones are different in their own way. The Gary Bernhardt talk "Boundaries" shows an end result that is very close to The Onion Architecture presented here. And Onion is of course very close to the also popular Clean Architecture and Hexagonal Architecture. Which at the end are very close to applications built using the principles that cjohnson318 mentioned: "have well defined interfaces, and pass simple data through them". This is all very close to some of the principles Bertrand Meyer teaches. For example, having different modules that make decisions and different modules that perform actions. Which is close to Event Sourcing and CQRS. Which once again is close to BASIC having SUBs and FUNs. Sure, under a microscope you will have different terminologies, and even apply different techniques and patterns, but the principles in the end are very similar. You might not have anti-corruption layers anywhere, as the sibling commenter mentioned, but that's missing the forest for the trees: the end goal and end result are virtually the same, even if the implementation is different. In the end happy families have different socioeconomic backgrounds, different ethnicities and religions, but they're still alike. It's the bad ones that have lots of special cases and exceptions everywhere in their design or whatever it is.
- pyinstallwoes 2y agoIndirection?
- Etheryte 2y ago> Imagine the most annoying possible client of our microservice. Suppose they want a new field, and they insist that it be named a certain way. This shows a fundamental misunderstanding of what code is for, at least in a production setting. Code isn't a marble statue that's supposed to be safely guarded in a museum, it's a way to get things done. Sure, for a hobby project you can polish it and perfect it like a diamond, but for business needs, the end goal of code is to do The Thing. That annoying client is why you're getting a high salary, if they didn't have their annoying needs, you wouldn't have a job.
- doctor_eval 2y agoThere is a lot more to meeting a customer’s needs than blindly doing what they say. Sometimes, you need to write code to protect them from their own (sometimes-but-not-always rational) decisions - or to protect other customers and stakeholder from them. You also need to keep your own team nimble. I’ve seen plenty of systems that have just thrown code at the product, and they end up with SQL tables with 150 columns - most of which nobody uses, and which can’t be removed, and the customer ends up pissed off anyway because you can no longer turn their requests around quickly. A good, layered design mitigates against this and makes it possible to continue to be productive even in the face of customer demands. Externalising customisations is a huge benefit to productivity.
- lexicality 2y agothis looks like it's describing the typical java horror where you have to make a generic interface to every single dependency to pretend you might be able to swap them out at some point and then you drown in a sea of interfaces and indirection trying to abstract everything into purity please just write plain code that's easy to follow, easy to debug and easy to delete! you don't need the survivability onion
- seanhunter 2y agoYes exactly. Anyone who has worked on big java codebases has at least one horror story where there are 10s or 100s of classes each with "use once" interfaces wrapping them and there are bizarre consequences like for example, there is only one possible way to wire the application up but for "flexibility" you have to go through (and occasionally debug) a spring boot nightmare for some reason anyway because somebody read a blog post on dependency injection and thought that was a good idea.
- jpz 2y agoThis article doesn’t define onion layering, I am none the wiser from reading it. There are near identical sentences within it, it gave me the sense I was reading AI generated content, or at least heavily AI post-processed content.
- Quothling 2y agoOnion layering is a non-scalable architecture which was immensely popular in the 00-10's due to how it interacts with OOP and it's somewhat crazy principles. It's based on seperating everything by interfaces in a structure which is a little similar to a MVC architecture. So you're going to organize your project(s) into a structure where you centralize everything with a seperation based on what "something" does. So you're going to put your OOP models in a specific place, your services in another and so on. As you can imagine it scaled horribly and today it's made completely obsolete by domain based architecture which is basically Onion Layering but both more reasonably organized and actually scalable. A lot of CS academics still live in a world where OOP is the greatest thing ever. Where things like wrapping functions in classes are necessary and where things like the onion architecture is still "modern". So naturally a lot of inexperienced developers, or developers who've never had to work on large projects, still hail it as the holy grail. Note that this was a very opinionated post.
- mech422 2y ago>>Note that this was a very opinionated post. Bonus points for calling it out as opinion, instead of treating it as the 'one true way' :-) P.S. I still like OOP well enough, and I love formal interface support like Go/Rust use. (Just IMHO)
- NicoJuicy 2y agoOnion, Hexagonal is pretty popular in the dotnet world and microservices. It's also overcomplicated for it's use-case and the main problem becomes mapping between layers and etc. Eg. One of the code-smells would be the Web.Abstractions layer. Just go with Vertical Slice Architecture. It dumbs everything down and if you need another technology as DB for example, you'll always need a migration of sorts, even if you have all the necessary abstractions. Note: Currently on a solo 4 month migration project going from Cognitive Search to Elastic, yes, we use "Onion".
- darkteflon 2y agoOT, but would you be inclined to elaborate on why you decided to migrate away from CS to Elastic? We’re currently considering CS.
- NicoJuicy 2y agoElastic search has snapshots ( iso deligation) and is cheaper/faster. Cognitive has no backups out of the box. Ps. ES has an SQLish language that makes it easier: https://rockset.com/articles/elasticsearch-sql/ https://rockset.com/articles/elasticsearch-sql/
- dgb23 2y agoI don't know what an onion is in programming terms. But each of those problems can be solved without one? --- 1. "Adding a field to our API" Parsing: You turn external input into an internal representation. 2. "Introducing a new downstream dependency" Essentially the same as above, but presumably bi-directional: You also turn your internal representation into something that is understood by your dependency. 3. "Introducing a new library dependency" I don't quite understand this example. Apparently writing a module that uses a third party library is an onion layer? --- Can someone explain what I'm missing?
- whalesalad 2y agoSeparation of concerns, essentially. https://blog.cleancoder.com/uncle-bob/2012/08/13/the-clean-architecture.html https://blog.cleancoder.com/uncle-bob/2012/08/13/the-clean-a...
- projektfu 2y agoThis particular article seems to advocate "adapt all the things!!!" using dependency injection to configure your adapters. I'd not come across onion architecture before but I'm a big fan of hexagonal architecture. The essential difference is that onion architecture wants dependency injection, adapters and a pure core, where pure just means no dependencies of any kind. Hexagonal architecture has the concept of internal and external, and advocates treating everything that is not part of the application as a consumer. In hexagonal architecture, a database may be an internal implementation detail, or it may be something external things expect to use and have a defined schema, etc. In the first case, it doesn't need special abstraction, in the second, it needs to be treated as something to adapt to. Onion architecture would say that it is a dependency and should be externalized from the start.
- mmastrac 2y agoThe article is describing, in a less clear way than they could, a clear separation of concerns in code. This is a good practice, especially for complex code. There is a tradeoff though: adding too many layers of indirection makes changes just as complicated as if you wrote a big ball of spaghetti (oh, just propagate this field across all 10 layers!), and that your team needs to be diligent about making changes to the correct layers. With a small, high-quality team this absolutely pays dividends in terms of ease of migration and changes, but you need to ensure there is good knowledge of the architecture spread across multiple people. The ideal place for this is in code with unclear, or rapidly changing business requirements. Note that this doesn't prevent you from getting bogged down by excessive complexity -- it literally just limits the blast radius of this complexity and makes the inevitable future refactorings smaller in scope.
- chipdart 2y ago> The article is describing, in a less clear way than they could, a clear separation of concerns in code. My take is a bit harsher. The article tries to reinvent the wheel -- poorly -- and fails to do the faintest and most superficial researches on a topic which is already covered in basic courses on software engineering. Layered architecture is a ubiquitous name in any work on software architecture, such as popular offshoots such as Uncle Bob's Clean Architecture. They describe the benefits of organizing software projects around layers, but go a step beyond and effectively solve the problem by also classify what kind of responsibilities should be assigned to each layer and how the dependency relationships between layers should be managed and enforced. I'm talking about basic principles such as internal/lower-level layers should contain code that changes the least frequently. There are also some software architectures which abandon the whole concept of layer and instead specify organizing the project in independemt submodules implementing/sharing common interfaces, and have root project handle only integration. This is often dubbed horizontal architecture as in all modules are laid out horizontally, as in they specify no dependency relationships with modules represented above or below, instead of vertically, as in modules are expected to comply with a fixed relationship archetype.
- mcphage 2y ago> adding too many layers of indirection makes changes just as complicated as if you wrote a big ball of spaghetti (oh, just propagate this field across all 10 layers!), and that your team needs to be diligent about making changes to the correct layers. "Layers of abstraction can solve any problem in software design, except for having too many layers of abstraction" :-)
- dekelpilli 2y agoAbstracting everything you use has a (high) cost, and doesn't always achieve what you want. This article repeatedly states things "go no further", but realistically, some dependencies will have worse inconveniences than a bad field name. If database you rely on is relational, has token based pagination, and has eventual consistency, chances are that swapping to a consistent timeseries DB with only limit/offset based pagination will impact code in your *.core.* package.
- usrbinbash 2y ago> Imagine the most annoying possible client of our microservice. Suppose they want a new field, and they insist that it be named a certain way. Then I tell the client that I sent him the API specification 2 months ago. If he isn't happy with it, he can write a wrapper himself. Of course, I could also change the API. Whether or not I do that depends on 4 factors in that order: 0) Do I have the time and resources to do so? 1) How important is the client? 2) How much does he pay me to do the change? 3) Exactly how annoying is the client?
- cangeroo 2y agoThe article is extremely short and by an unknown author, so there isn't much to discuss. But I've met many people who hated onion architecture with a passion. I have a few theories: - Maybe a lot of programmers have ADHD, are autistic, or suffer from dyslexia, and find planning, naming, designing abstractions as excruciating activities. - Onion architecture etc. is a long-term strategy that mainly benefits the company/project owner, but not the individual contributor. So it basically has to be forced upon programmers, who will resist it in every way possible, because they have no real incentive to use it. - It's supposed to make writing software easier. But it really requires an IDE that's designed for abstractions, such as IntelliJ, and also requires a different way of working with the code. It's also verbose. So it's really a different paradigm, and it won't work if you use a plain text editor. You'll drown in code and a vast number of files. - Onion architecture is not OOP, but often mixed in with enterprise OOP, and therefore bad associations that come with enterprise OOP. Any other thoughts on why people resist it so much? And what changes in how we work with code, would make onion architecture more practical?
- victorNicollet 2y ago> Onion architecture etc. is a long-term strategy that mainly benefits the company/project owner, but not the individual contributor. So it basically has to be forced upon programmers, who will resist it in every way possible, because they have no real incentive to use it. Although I was aware of it for a while now, I had never seen this misalignment (between what I called ease-of-writing and ease-of-maintenance) stated so clearly in so few words. Thank you !
- djeastm 2y ago>- Maybe a lot of programmers have ADHD, are autistic, or suffer from dyslexia, and find planning, naming, designing abstractions as excruciating activities. I don't know about the medical conditions, per se, but I think this does bring up a point that is often overlooked when discussing best practices: our brains are different and organize things in different ways. What works and makes sense to one group of people might not work or make sense to another group of people. I find that more literal-minded people are frustrated by what they see as unnecessary abstraction and are fine with duplicated code whereas people who think in abstractions have no problem seeing the bigger picture and are proponents of abstractions when the abstractions make sense to them. I have coworkers who will look at a codebase with a layered/onion architecture and immediately understand and reuse all of the abstractions without issue and others who will immediately want to simplify it and change it all into concrete implementations. I find myself to be fairly evenly split so I see it from both sides. I think it's often more about the nature of the latest person who looks at the codebase than the codebase itself. Eye of the beholder and all that.
- joshstrange 2y agoI think layers are important (All internal data should be mapped onto DTOs to returned to a client IMHO) but it's also important to not have more than 2 layers to get to the core, ideally 1. I've worked places before where they have you call through a function that calls a function that calls a function (replace "function" with "api endpoint" in some cases) because "Well we know function X works and so just call it", then fast-forward a year or two "Well we know function Y works, which calls X, so it's safest if you call Y, don't call X" and so on. This leads to a complete mess and tons of inefficiencies. Often "X" over/under-fetches what you want so you either have to throw away some of the result or add to it. I've even seen cases of Z->Y->X where X over-fetches, Y only uses a subset, and then Z has to re-fetch the data that Y threw away. All because someone decided an arbitrary layer is the new golden standard that everything should be built on.