Home Backend Development Python Tutorial Clean architecture: Where to start ?

Clean architecture: Where to start ?

Dec 07, 2024 am 09:59 AM

Clean architecture: Where to start ?

In the previous post we have:

  • Our problem domain: a ToDo application with some requirements
  • A basic repository configured to use Python and Python Polylith.

So, some decisions are taken care of. We have some of the tools and have decided what the repository will look like.

This is one of the things that I love about Polylith: it doesn't matter what you're coding or how big your organization is, all the repositories will look the same - if you need more than one.

Your repository structure is consistent, whether you're using FastAPI, Flask, or Django, building single or multiple libraries, or running background tasks with Celery.

One of the key advantages is the streamlined onboarding process for new developers. Assuming they have a grasp of Polylith, they'll quickly become familiar with the project structure: reusable components are in the components folder, entry points are in the bases folder, demo scripts are in the development folder, and so on.

Entities

From Uncle Bob "The Clean Architecture" entities are the cornerstone of our architecture, they are the most inner layer of our architecture. So we need to start with them, in Polylith entities should live as components.

How many components?

I believe the number of components depends on the size and complexity of your solution. However, I recommend starting with a single polylith component for entities. This approach helps maintain a clear and focused architecture, especially for smaller projects.

Why a single component for entities?

  • This layer encapsulates core business rules that are fundamental to the entire application. By keeping it in a single component, you ensure consistency and avoid duplication.
  • A single component simplifies dependency management, as it becomes a dependency for all other layers.

Avoid third-party dependencies.

To minimize external dependencies and enhance architectural flexibility, strive to use Python's standard library for representing entities. This includes leveraging data structures like dict, list, enum, functions, classes and more recently dataclasses.

Why avoid third-party libraries like Pydantic or Django Models?

  • Coupling to external frameworks: Relying on these libraries can introduce unnecessary coupling to specific frameworks.
  • Increased complexity: External libraries can add complexity and potential maintenance issues.
  • Reduced flexibility: By limiting external dependencies, you can more easily adapt to changes in requirements or technology.

By adhering to these principles, you can create a robust and maintainable architecture that is resilient to future changes.

ToDo entities

Our example is straightforward, with the core entity being the "todo item" for Gordon. We can add a new component to our repository, but choosing the right name is crucial.

While it might be tempting to use generic names like "core" or "main," it's essential to select names that are meaningful within the domain context. Ideally, these names should align with the terminology used by the client or product owner. By using domain-specific names, we enhance code readability and maintainability, making it easier for both developers and stakeholders to understand the project's structure.

The repository workspace name is defined as todo. Consequently, all our imports will follow the format:

from todo.XYZ import ...
import todo.XYZ
Copy after login

For simplicity in this example, we'll use entities as the component name. However, in real-world scenarios, consider naming conventions that reflect your domain. For instance, if your application revolves around document recovery, a component named recovery would be appropriate. Similarly, a gaming application might use tournaments_entities for clarity.

Creating the component with Python Polylith is simple:

poetry poly create component --name=entities
poetry poly sync
poetry install # it may be necessary
Copy after login

This will add a python package in the components folder, this are the new entries in the source tree:

./components
└── todo
    └── entities
        ├── __init__.py
        └── core.py
./test/components
└── todo
    └── entities
        ├── __init__.py
        └── test_core.py
Copy after login

The python-polylith tool will generate test examples for us, which is a nice feature. This behavior can be changed in the workspace.toml file by setting the enabled = true value to false in the [tool.polylith.test] section.

In the new entities component, two files are added: __init__.py and core.py. You can rename the core.py module to better suit your needs. The common practice is to expose the public API of the package through __init__.py, while maintaining internal organization within other modules like core.py.

From the requirements, we has, at the moment, only one entity, the ToDo item:

@dataclass
class TodoItem:
    owner: str
    title: str
    description: str
    is_done: bool = False
    due_date: Optional[date] = None

Copy after login

Testing such a simple entity might seem unnecessary, but I prefer to test at least the presence of all fields. While this may not seem crucial in smaller projects with fewer contributors, it can prevent significant issues in larger projects with many developers. Removing a single field from the entity can inadvertently break various parts of the application.

In the pull request for this part, you will see that i have added some basic tests for this entity.

With some tests already defined, I took the opportunity to add a GitHub workflow to automatically run the tests for each pull request.

Conclusions

  • Application basic entities
  • CI setup

What is next: Let's talk about persistence

The above is the detailed content of Clean architecture: Where to start ?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. Have Crossplay?
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to solve the permissions problem encountered when viewing Python version in Linux terminal? How to solve the permissions problem encountered when viewing Python version in Linux terminal? Apr 01, 2025 pm 05:09 PM

Solution to permission issues when viewing Python version in Linux terminal When you try to view Python version in Linux terminal, enter python...

How to efficiently copy the entire column of one DataFrame into another DataFrame with different structures in Python? How to efficiently copy the entire column of one DataFrame into another DataFrame with different structures in Python? Apr 01, 2025 pm 11:15 PM

When using Python's pandas library, how to copy whole columns between two DataFrames with different structures is a common problem. Suppose we have two Dats...

How to teach computer novice programming basics in project and problem-driven methods within 10 hours? How to teach computer novice programming basics in project and problem-driven methods within 10 hours? Apr 02, 2025 am 07:18 AM

How to teach computer novice programming basics within 10 hours? If you only have 10 hours to teach computer novice some programming knowledge, what would you choose to teach...

How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading? How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading? Apr 02, 2025 am 07:15 AM

How to avoid being detected when using FiddlerEverywhere for man-in-the-middle readings When you use FiddlerEverywhere...

What are regular expressions? What are regular expressions? Mar 20, 2025 pm 06:25 PM

Regular expressions are powerful tools for pattern matching and text manipulation in programming, enhancing efficiency in text processing across various applications.

How does Uvicorn continuously listen for HTTP requests without serving_forever()? How does Uvicorn continuously listen for HTTP requests without serving_forever()? Apr 01, 2025 pm 10:51 PM

How does Uvicorn continuously listen for HTTP requests? Uvicorn is a lightweight web server based on ASGI. One of its core functions is to listen for HTTP requests and proceed...

What are some popular Python libraries and their uses? What are some popular Python libraries and their uses? Mar 21, 2025 pm 06:46 PM

The article discusses popular Python libraries like NumPy, Pandas, Matplotlib, Scikit-learn, TensorFlow, Django, Flask, and Requests, detailing their uses in scientific computing, data analysis, visualization, machine learning, web development, and H

How to dynamically create an object through a string and call its methods in Python? How to dynamically create an object through a string and call its methods in Python? Apr 01, 2025 pm 11:18 PM

In Python, how to dynamically create an object through a string and call its methods? This is a common programming requirement, especially if it needs to be configured or run...

See all articles