139 points · by rekahrv · 3y ago · 75 comments
One recommendation I have is to present the hierarchy as DAG. Existing image (https://sourcery.ai/static/05300f06cb847360719e2aa31dc5a31b/...) doesn't make it very obvious that api is a highest-level module, even though it is clearly stated in the rules.
Doing it manually allows me the following:
1. I get to define what are the namespaces (domains) that matter, irrespective of the package structure. E.g. import from stripe.api_resources is still a dependency on stripe, not on stripe.api_resources.
2. Work around a bunch of dependency caveats (frameworks like Django do runtime imports and mix high and low level concepts in settings, db foreign keys might inverse your dependencies, etc)
3. Violations are very easy to see: they are cycles in the graph, i.e. arrows pointing upwards. Those are typically design flaws. Though I still allow certain violations because practicality beats purity.
4. Since some violations are allowed, I get to decide how to arrange the graph so that it is more clear what is the flaw and how to address it.
I haven't found a good tool that allows me to get all of these. One day I'll have to build it myself.
* Visualization gives a better overview. * Rules as code allows more fine-tuning. E.g. explicitly allowing those few exceptions you mentioned in point 3.
To your points: 1. I absolutely agree. No dependency to Stripe also means no dependency to any of Stripe's subpackages. (The article should probably emphasize this more.) 2. This is a good point. The rules generated for Sourcery only check `import` and `from ... import` statements. Runtime imports are (for now) out of scope.
To Sourcery's credit, their product looks much more in the realm of "developer experience" -- closer to Copilot (or what I understand of it) than to import-linter. Props to them for at least having a page about security [2] and building a solution which doesn't inherently require all of your source code to be shared with a vendor's server.
[0] https://github.com/seddonym/import-linter
[1] https://www.pantsbuild.org/
[2] https://docs.sourcery.ai/Product/Permissions-and-Security/
Rewriting a lot of things was time well spent rather than trying to tame the dynamic nature of Python and my tendency to overuse it.
And I can't believe I'm writing this after all these years evangelizing Python and dynamically typed languages.
I've been fighting battles in Python backend services to get a nicely decoupled API, logic and DB layers for a while...but sqlalchelmy, alembic and flask/django/fastAPI are my safety blankets
I’ve done a lot of C# and Java now over the last few years, and I don’t love their type system, esp compared to typescript, but they scale much better against large codebases - especially with tooling like bazel.
I’ve been looking at Haskell and Rust a lot to fill this intermediary: code that’s performant, with a very expressive type system.
I maintain(ed) a number of popular python packages, and that journey lasted for nearly a decade.
I ended up being very happy with F# as a middle ground for several years, but eventually migrated back to C# as they started adding more and more F# features. The primary challenge with F# was the parity mismatch with the underlying runtime, so you end up having to write a fair amount of non-idiomatic F# to interop with common libraries. But otherwise it's great. (I also tried Scala for a year and hated it: too many ways to do any one thing).
As for the reasons:
- Static typing and C# projects makes code organization and refactoring dead easy.
- Modern C# doesn’t require that much boilerplate, and has features that allows a developer to speed up development, like Python.
- EF Core covers everything I need from SqlAlchemy/Alembic.
- LINQ is an awesome way to work with collections. Type safe DB queries comes handy both when developing and refactoring.
- ASP.NET covers everything I need from flask/Fastapi.
- More speed and lower resource usage is nice.
- Being able to use an IDE with it’s full power is nice.
My main reason to switch was static typing, and my only requirement was a good ORM comparable to SqlAlchemy. The rest is just bonus.
> - Being able to use an IDE with it’s full power is nice.
In my experience, Visual Studio is much slower when developing. My Python workflow affords a 200ms red-green-refactor loop, while VS is on the order of several seconds.
This might not seem like much, but it has a great impact on my engagement, flow, and satisfaction.
Another reason is that decoupling and adding layers to your code is more part of the culture. Look up “domain driven design C#” or “onion architecture C#” and there will be a lot of resources on how to achieve it. There is stuff out there for Python as well (and the concepts translate between languages), but not nearly as much.
It feels a lot more professional than other ecosystems. For example, they actually talk about layering/coupling as professionals should! People actually seem to talk about architecture as well rather than blindly believing that the conventions forced on them by a framework are sufficient for all use cases.
I especially like the gradient in the .NET world from micro ORMs to full-fledged ORMS. Most ecosystems seem to develop a big ORM that constantly accrues features (and bugs) and eventually becomes enshrined as a "best practice" because it acts as a kitchen sink.
(I don't do this using sourcery though ... I have my own set of rules)
Basically, you have an api class for each Django app, and you use this class for all external interactions. The api class calls the service class, and the service class deals with the Django ORM. I added a view class, which is my DjangoRestFramework layer; so when a request comes in, it's caught by my view class, and passed onto the api class. I have DRF serializers for outgoing data, and pydantic schemas for incoming data. I also have a selector class for read-only views of my data.
It's a lot of typing, but I know exactly where everything is when something goes wrong, or I need to add a small adjustment somewhere, also it's easy for new devs to learn and use. One downside is that an api change require you to touch a dozen files.
I have had trouble using Django API Domains interfaces.py, so I left them out. The main point is, figure out the right balance of concise code and separation of concerns for your taste, and your stack. Good luck!
"For example, a high maturity package is not allowed to depend upon a low maturity package. Similarly, a core library package is not allowed to rely on a package that is specific to a particular product or a particular piece of bespoke development." I really like these.
Some of this metadata gives traceability information for requirements, tests etc.. while other metadata enables me to associate a maturity level with each file.
My build system understands this metadata and uses it to inform e.g. the minimum test coverage that it expects on a file-by-file basis.
The same metadata is used to ensure that all of the other components that a file references are at the same level of maturity or higher.
I also have metadata for each file (partly derived from location in the repository) that gives each file a number which defines it's position in a hierarchy of design elements.
The position in the hierarchy helps to indicate what the purpose of the file is. I use this to make a distinction between those core, foundational, stable design elements upon which other design elements may build, and those more peripheral, ephemeral and 'agile' design elements which can be quickly tailored to meet the needs of a client or partner.
This means that a (hopefully stable) core API component can be prevented from relying upon a (perhaps less stable) bespoke customer-specific component. It also means that there's more freedom in changing and adapting peripheral designs as you can have confidence that it's stability is not something that is going to be relied upon.
"It also means that there's more freedom in changing and adapting peripheral designs as you can have confidence that it's stability is not something that is going to be relied upon." That's a big advantage, indeed.
I also like the concept of storing this metadata next to the code in structured comments.
Just to nitpick, while it is a very potent foot-gun, Python absolutely does allow circular dependencies between regular modules; here's a good write-up about this:
I seen some very legacy database 'designs' and have never failed to model them with a combination of sqlalchemy join mapping, datatype mapping and some object properties in python for cases that are simpler to just express as list comprehensions.
You end up with some data quality rules / Transformation logic you can reasonably share with business users.
On the Load end I normally do that via sql bulk inserts as using an ORM just adds too much overhead and not enough control.
"Once you've got that feature as a way to tame a larger and expanding codebase, you'll wonder why it isn't a feature in more systems." :-)
Storing the API model in your DB is really a bad idea.
I'm (maybe obviously) on the SOA-skeptic side, my arguments generally are:
- Most apps aren't that big and don't need multiple layers of abstraction (i.e. the ORM and its models are totally fine). If the app starts getting too big for its britches, probably the best thing to do is make it 2 apps (too big: 2 apps is a good slogan here).
- Dependency injection and mocks are pretty bad ideas that are only occasionally useful (DHH uses the example of a payments gateway), but mostly push IoC through your whole app and make control flow confusingly backwards. Mocks are always in disrepair, and almost never accurately reflect what they're trying to mock, and thus ironically are big vectors for bugs that make it through testing.
- Having tons of unit tests tends to slow eng velocity to a crawl, because they test the parts of the application that aren't the requirements (were these functions called, what's the call signature of this function, was this class instantiated, etc.). Unit tests create a super-fine-grained shadow spec about the lowest level details of your application, and mostly I think they shouldn't ever be committed to a repo. They help during individual development, but then the whole team is stuck maintaining them forever whenever they make changes. They also tend to slow down CI because they're slow and always flaky.
- You almost certainly will never need to switch databases, let alone abstract across a database, a message queue, and a web api. It's not worth doing a "repo" abstraction and encapsulating those details.
- There are (now) really good libraries for almost anything you want to do. ORMs literally map database entities to domain entities--they just abstract the persistence for you. Sounds like a repo to me! We also have good validation, logging, monitoring, auth/auth etc. built into frameworks and 3rd party services. A lot of the things you might put into other layers or even other services are now neatly packaged into libraries/frameworks you can just use and SaaS things you can just buy, leaving you free to just implement your business logic.
>They also tend to slow down CI because they're slow and always flaky.
In my experience, unit tests are the most stable, the least flaky, because they touch the least code and often have very simple setup. An integration test might rely on four database tables being just-so, and go on to connect with two external services (and whether mocked, replayed, or live, flakiness may arise). That integration test is twenty times more valuable, but it is equally more likely to break for reasons tangential to its core assertions.
Disagree on dependency injection. I came from the globals/patch everything school of python, to the Fastapi/Pytest DI flavor, and it's a breath of fresh air. It's just so much easier to abstract the IO providers and swap them out with objects tailored to the test suite - eg for database, I create db objects which roll back any transactions between tests.
Hard disagree on unit tests. Maybe in other languages, but in Python, trying to develop even a moderately complex app without unit tests is a nightmare. I know, I've lived it. Even in an app with >85% unit test coverage, there was still a ton of friction around development on any of the interfaces which had low coverage.
Any gains in velocity of development almost always cost far more in debugging down the road.
I love python, but it is really prone to dumb footguns at runtime, NoneType errors in particular. You need to impose a lot of discipline to make large python apps enjoyable to develop on.
Often, engineers (and HN) forget that code is a means to an end - not an artistic expression that provides value by its pure existence.
When your apps live as a service on the network or as a nicely isolated module in your repo, you no longer have a reason to over-engineer them. You don't need a grandiose architecture that solves every problem, instead you can make local decisions that are good enough in the specific context. Though, admittedly, I found it hard to sell such "inconsistencies" to other tech leaders, most folks aspire to those grandiosities.
> If the app starts getting too big for its britches, probably the best thing to do is make it 2 apps
That's the argument in favor of SOA, isn't it?
IMO, the FastAPI approach you described makes a lot of sense: The "schema" stored in the db and the "schema" returned by the API aren't the same, but they are quite similar. They have many common properties => They can often have a common base class.
[0] https://learn.microsoft.com/en-us/dotnet/architecture/micros...