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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

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 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...

How to solve permission issues when using python --version command in Linux terminal? How to solve permission issues when using python --version command in Linux terminal? Apr 02, 2025 am 06:36 AM

Using python in Linux terminal...

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 get news data bypassing Investing.com's anti-crawler mechanism? How to get news data bypassing Investing.com's anti-crawler mechanism? Apr 02, 2025 am 07:03 AM

Understanding the anti-crawling strategy of Investing.com Many people often try to crawl news data from Investing.com (https://cn.investing.com/news/latest-news)...

Python 3.6 loading pickle file error ModuleNotFoundError: What should I do if I load pickle file '__builtin__'? Python 3.6 loading pickle file error ModuleNotFoundError: What should I do if I load pickle file '__builtin__'? Apr 02, 2025 am 06:27 AM

Loading pickle file in Python 3.6 environment error: ModuleNotFoundError:Nomodulenamed...

What is the reason why pipeline files cannot be written when using Scapy crawler? What is the reason why pipeline files cannot be written when using Scapy crawler? Apr 02, 2025 am 06:45 AM

Discussion on the reasons why pipeline files cannot be written when using Scapy crawlers When learning and using Scapy crawlers for persistent data storage, you may encounter pipeline files...

See all articles