Clean architecture - Hexagonal architecture, Screaming architecture, DCI, BCE

Last updated Jan 5, 2025 Published Aug 18, 2023

The content here is under the Attribution 4.0 International (CC BY 4.0) license

Part I - Foundation

Separation of concern, isolating pieces of code that repeat and decoupling responsibilities from different parts of the code base seems to be a common approach among experienced developers. Maximiliano Contieri for example, named coupling the only software design. Therefore, through the experience comes the opinionated approach, some developers might decide to create specific directories or others might use longer file names to express intent.

I have published my thoughts on that matter as well, and then I discovered the clean architecture book [1], which dives much deeper on that subject and also explores the pros of having an architecture in place. In his keynote talk “Agility and Architecture” Uncle Bob emphasizes that elements like the web, database, or user interface should be treated as implementation details, not as drivers of an application’s architecture.

This perspective aligns closely with the principles of Clean Architecture, which prioritizes independence from frameworks and external systems. In the next section, we’ll explore how Clean Architecture compares to other architectural styles, examining its unique approach to maintaining flexibility and adaptability.

Architectural styles compared to the clean architecture

As I first started my path through clean architecture I often found myself asking myself: is hexagonal architecture [2] the same as clean architecture? The clean architecture, shares decisions compared with the hexagonal architecture, as Uncle Bob [3] states that the clean architecture is an attempt to integrate the hexagonal architecture and others as well, named:

  1. Hexagonal architecture / Onion architecture
  2. Screaming architecture
  3. DCI (Data, Context and Interaction)
  4. BCE (Boundary, Control, Entity) [4]

Clean architecture is an attempt to combine those styles to produce an output, in short, it tries to combine the good parts of every other style into one, aiming at provide applications maintainability and focus on the business domain rather than on technical details that arew unknown (or might change). With that in mind, let’s go over the building blocks of this architectural style.

Clean architecture at a glance

Clean architecture focuses on the separation of concerns and also takes care of the evolution of the code, the evolution is one of the key aspects of clean architecture as it has a dedicated section in the first chapter, “The Total Cost of Owning a Mess”, [1] that depicts the fact that the productivity degrades as the time goes. Which is caused by the lack of care with code and also the software maintainability. The following diagram taken from [3] depicts the clean architecture overview that as a goal has the clear distinctions of responsabilities and to isolate what is details and what are business.

Clean architecture diagram

The structure of this post mirrors the one presented in Uncle Bob’s Clean Architecture book[3], as it provides a well-established framework for understanding the topic. However, while the organization closely follows the book, I’ve taken care to use my own words throughout, with the goal of the content reflects my perspective and voice.

The dependency rule

The dependency rule follows the same principle as the layered architecture. [5]. Anything in the inner circle should not know anything about the outer circle, the same principle in the layered architecture, to keep layers following the same direction. This rule is oriented to to the rate of changes. Inner dependencies are most likely to change less in comparison to outer dependencies. Changes can be updates, upgrades and migrations.

Entities

Entities are the objects that represent the business. In applications that serve users and support business, throught my journey in the server side applications space, I saw entities being used as a 1 to 1 mapping to the database. However, entities are not stricly confined to this approach, they can be a simple class that has methods or a datastructure that represents a meaninful organism.

Use cases

Use cases are the business rules that the application executes. Here is the place to add the business logic. In a comparison with MVC, I would argue that, the use case is the place where the controller is, if the controller is the place that the logic for business are. It can be split into the controller and the model (it might vary from application to application).

The use case that underlines the architecture style was heavily influenced by the book “Object Oriented Softare System A use case driven approach” that Ivar Jacobson wrote. In the talk Clean architecture and Design presented at NDC 2013 it is stated the inspiration that drove this decision.

The use case drives the architecture

After watching an introductory talk about the clean architecture by its author, I came to realize that 10 years ago I also was on the wave that he describes as fiasco of use cases. In 2015 I developed and published a tool named “UseCaseManagement” that was developed by my colleagues and myself.

Frameworks and adapters

Opposed to what MVC frameworks impose in the architecture for web applications, the clean architecture does not take the framework as something that is the core of the application, instead the framework is something that is an “implementation detail”, meaning that it is possible to change the framework choice if needed, without impacting the use cases. The same way as the framework is a detail the database is as well [3].

SOLID

In the clean architecture book, the conception of this architectural style also target the usage of SOLID principles, as a guiding principle for designing this architecture. In fact, the book that conceived this new archiitiiiectural style dedicates a section named “Part III Design Principles” to talk about each concept in SOLID [1].

Implementation details

The book comes with code examples to illustrate the scenarios and also to make statements on the point being made, therefore, there is no folder structure, file name convention or whatsoever to “glue the pieces together”. This is a point to improve, but not necessary in the book. I would argue that for any programmer with a few years of experience, the concepts given are understandable, but there are programmers like me who like some sort of guidelines so that it is possible to compare implementations.

Hombergs provides an implementation of clean architecture using java [6]. It goes along the clean architecture definitions and depicts folder structure, files, boundaries, and abstractions and also reinforces definitions on the use cases.

Clean architecture check point

1. What is the main goal of Clean Architecture?
2. What is the Dependency Rule in Clean Architecture?
3. What are Entities in Clean Architecture?
4. What is the role of Use Cases in Clean Architecture?
5. What is the relationship between Clean Architecture and SOLID principles

Foundation References

  1. [1]R. C. Martin, “Clean Architecture A Craftsman’s Guide To Software Structure And Design,” 2017 [Online]. Available at: https://archive.org/details/CleanArchitecture/page/n179/mode/2up. [Accessed: 2020-Jun-11AD]
  2. [2]A. Cockburn, “Hexagonal architecture,” 2012 [Online]. Available at: https://alistair.cockburn.us/hexagonal-architecture. [Accessed: 13-Aug-2012]
  3. [3]R. C. Martin, “The Clean Architecture,” 2020 [Online]. Available at: https://blog.cleancoder.com/uncle-bob/2012/08/13/the-clean-architecture.html. [Accessed: 07-Oct-2020]
  4. [4]I. Jacobson, “The use-case construct in object-oriented software engineering,” in Scenario-based design: envisioning work and technology in system development, 1995, pp. 309–336.
  5. [5]R. Mark, Software Architecture Patterns. O’Reilly Media, Inc, 2015.
  6. [6]T. Hombergs, “Get Your Hands Dirty on Clean Architecture - A Hands-on Guide to Creating Clean Web Applications with Code Examples in Java,” 2020 [Online]. Available at: https://leanpub.com/get-your-hands-dirty-on-clean-architecture. [Accessed: 30-Jan-2020]

Foundation Additional resources

As a companion for this post, I recommend the talk “The Principles of Clean Architecture” by Uncle Bob Martin as well as the playlist that I built on software architecture in general [7].

Part II - Practice

In this second part, we build upon the concepts introduced in the previous section to demonstrate their implementation in code. Through practical examples, we will explore the strengths and weaknesses of the approach, provide comparisons, and share additional insights to deepen your understanding.

Backend implementatio in PHP

Clean Architecture principles are highly adaptable and can be applied to a wide range of domains. To illustrate their practical application, this post introduces a fictional domain designed to streamline the release process of tags in GitLab through automation. In the following subsections, we will:

  1. Outline the specific challenges this domain addresses and explain the motivation behind automating the release process that became the project “Git Bot”
  2. Walk through the implementation step by step, showcasing how Clean Architecture principles guide the design

Git Bot Concept

Git Bot is a tool designed to automate the often tedious task of version management in software projects. It is built on two key industry conventions:

How Git Bot Works

At its core, Git Bot integrates with a Git repository and monitors activity through webhooks. Specifically, it listens for pushes to designated branches, which can be configured via the Git Bot web interface. When a push is detected, Git Bot processes the commit (or commits) included in the push and analyzes their titles for a specific pattern:

chore: tagged version x.x.x  

Versioning Constraints

As a proof of concept, Git Bot currently enforces a simplified versioning format. Versions must be numeric and follow the major.minor.patch structure, such as:

chore: tagged version 10.2.0

Non-numeric versions or additional identifiers, like release candidates (-rc), are not supported at this stage. For example, the following would not be valid:

chore: tagged version 10.2.0-rc  

Automating File Updates

Once Git Bot detects a valid version tag in a commit title, it automatically updates the relevant versioning files (e.g., package.json, composer.json, or others). This eliminates the need for manual file edits, reducing errors and ensuring consistency across the project.

Git bot Workflow Overview

The following illustrates the Git Bot workflow:

  1. A push is made to the monitored branch.
  2. Git Bot receives and analyzes the commit(s).
  3. If a version match is detected, Git Bot updates version files.
  4. Changes are pushed back to the repository.

Git bot Structure overview

Given that the application is a PHP one based on composer, the structure followed the standard for PHP APIs, the adopted structure was inspired by the previous section on clean architecture. Let’s start with a folder representation of the resulting application. The following folder structure has been condensed for readability, ensuring it takes up less space on the page. For a complete and detailed view of the entire project structure, you can explore the full repository on GitHub.

src
├── Domain
│   ├── ConventionalCommit
│   │   ├── FilesUpdater.php
│   │   └── VersionMatcher.php
│   │   └── VersionToReleaseNotFound.php
│   ├── GenerateRelease
│   │   ├── Assembly.php
│   │   └── Dispatch.php
│   └── Gitlab
│       ├── Authentication
│       │   ├── CouldNotEraseTokenException.php
│       │   ├── TokenMiddlewareChecker.php
│       ├── Entity
│       │   ├── File.php
│       │   ├── Release.php
│       │   ├── Settings.php
│       │   └── Webhook.php
│       └── Webhook
│           └── WebhookRepository.php
├── Infrastructure
│   ├── Gateway
│   │   ├── Gitlab
│   │   │   ├── FileApiRepository.php
│   │   │   └── WebHookApiRepository.php
│   └── Persistence
│       ├── FilesystemDatabase.php
│       └── Gitlab
│           ├── SettingsFilesystemRepository.php
│           └── TokenFilesystemRepository.php
├── UseCases
│   └── Gitlab
│       ├── Authentication
│       │   └── RequestToken.php
│       ├── File
│       │   ├── DeleteFileToBeReleased.php
│       │   └── SaveFileToBeReleased.php
│       ├── Project
│       │   └── Details.php
│       ├── ProjectList.php
│       └── Settings
│           ├── GetGitlabSettings.php
│           └── SaveGitlabSettings.php
└── Web
    ├── Actions
    │   ├── ActionError.php
    │   ├── ActionPayload.php
    │   └── Gitlab
    │       ├── Auth
    │       │   └── Unauthorized.php
    │       ├── File
    │       │   └── Delete.php
    │       ├── Projects
    │       │   └── Detail.php
    │       ├── Settings
    │       │   └── Save.php
    │       ├── Webhook
    │       │   └── Register.php
    │       └── Welcome.php
    └── Routes.php

Each folder was created targeting the following elements of the clean architecture:

Clean architecture concept Implementaion in the API
Frameworks and Drivers Web folder
Interface adapters Web folder
Application business rules Use cases folder
Enterprise business rule Use cases folder

Frontend implementatio in ReactJs

In the frontend space the clean architecture principles are also a subject that developers target in the aim to develop maintable applications. However, in the other side of the stack, the needs and challenges are not necessary the same, for example, while in the backend the database might be treated as an implementation detail, in the frontend the storage might be an API, a browser API (such as local storage or indexed db). In addition to that, the frontend is also not treated as an implementation details, this is the space that the users will interact wit the application. In the following subsections of the frontend we will:

  1. Explore the itext tool concepto and why it was developed. This is a project with fictional domain that was used as an example.
  2. Walk throug the implmentaion of Clean Architecture

Text tool Concept

Text-tool is an open source application designed to assist developers with common text-related tasks. It provides functionalities such as:

  • Word Count: Quickly calculate the number of words in a given text.
  • Word Frequency Analysis: Identify the most frequently used words in a text.

The tool aims to reduce the manual effort involved in these repetitive tasks, and it focus on privacy, no tracking is done.

How text tool Works

Text tool provides an interface that users can drop the text in the main area and on the right there will the the stats listed. On the bottom the users will be able to set stop words to be used or not by the statistics.

text-tool

Text tool Structure overview

src
├── index.tsx
├── presenters
│   └── word-count.ts
├── reactjs
│   └── App.tsx
└── use-cases
    ├── types
    │   ├── StopWords.ts
    │   └── types.ts
    └── words-count.ts

Resources for frontend and clean architecture

  • React Clean Architecture: A Guide for Scalable, Testable Apps - There is an effort to illustrate how the concepts of Clean Architecture can be translated into the React.js ecosystem, with specific layers such as the View Layer, Use Case Layer, Repository Layer, Adapter Layer, and Service Layer. While the text introduces these concepts and explains their roles within the architecture, it does not provide concrete examples of applications developed using this approach.
  • Build a React Application With Clean Architecture - The blog post uses a tic-tac-toe game as an example to demonstrate how Clean Architecture can be applied. Domain-Driven Design (DDD) is also briefly introduced within the context of the example, encapsulating its principles into the design. For instance, the Board entity represents a small but crucial part of the business logic, showcasing that entities are not merely 1-to-1 mappings to database tables but instead encapsulate significant business rules and behaviors. Additionally, the post explores dependency injection (DI) using React’s context API, which differs from the approach recommended in the book “React Clean Architecture: Redefining React Application Design in the Context of Clean Architecture.” While the book primarily demonstrates how to use a library for DI, it does not provide an in-depth implementation within its examples. Conversely, the blog post offers a practical perspective by applying DI directly through context. From the shared content, it appears the author combines principles from Clean Architecture to interpret and structure the application. However, while the blog post provides valuable insights and concepts, it does not offer the full source code for detailed inspection, limiting a deeper understanding of the implementation.
  • React Anti-Patterns

Other approaches for architecture

Not until recently I have come across a book that depict different approaches for organizing a project when taking into account large applications [8]:

  • Default structure (which comes with the predefined framework of choice)
  • Feature/domain-based organization

Part III - Conclusion

In this post, we explored the principles of Clean Architecture, emphasizing its focus on separation of concerns and the evolution of code. It has shown how Clean Architecture integrates concepts from other architectural styles like Hexagonal Architecture, Screaming Architecture, DCI, and BCE to form a robust approach to software design.

For the backend, the practical application of Clean Architecture was demonstrated through the example of “Git Bot,” a tool designed to automate version management in software projects. Git Bot integrates with Git repositories and monitors activity through webhooks. It processes commits, detects version tags, and updates version files, all while adhering to the principles of Clean Architecture.

On the frontend, we showcased how Clean Architecture can be implemented in React.js through a “text-tool” application. This example demonstrated how to structure a frontend project to maintain separation of concerns, and the applicability of Clean Architecture.

Part IV - Discussion

Real applications and abstraction from implementation details from the framerwork

The idea of inverting the dependency in an architectural style is appealing because it provides the following benefits:

  1. boudaries between the application and the framework
  2. repleceability, as it depends on an interface it will be able to replace that with anothjer framework in the future

However, for point number 2, the theory shows as a guideline more than a rule to be implementent, appliucations that are built for business purposes usually are built on top frameworks instead of being one point of dependency. Making the choice of which framework to use a critical decision for any application that aim at supporintg businesses.

Clean architecture in details

1. Which author was the inspiration for Uncle Bob to make use of use cases in the Clean Architecture?

Part V - Where to go next

  • 12 factors to consider when chosing frameworks - Last accessed Jan 08, 2025: In the discussion presented so far, the framework layer in Clean Architecture has been intentionally given less attention. This omission aligns with the principle that the framework is treated as a detail, separate from the core business logic, and not the primary focus of design. However, the choice of framework is significant because it underpins and coexists with the application throughout its lifecycle. Matthew W. O’Phinney, in a blog post, outlines 12 critical factors for selecting a PHP framework, such as error handling, deployment support, data storage flexibility, and rapid application development capabilities. While his post focuses on PHP, these considerations resonate across technologies and are particularly relevant when evaluating frameworks in the context of Clean Architecture. For instance, a framework’s support for modular design or clean error handling can directly impact how seamlessly it integrates with the application’s core logic. By aligning framework selection with architectural principles, teams can ensure that this “detail” enhances rather than hinders their software’s maintainability.
  • GOTO 2018 Modular Monoliths - Simon Brown - Last accessed Jan 11, 2025
  • Architectures of modern Front-end applications - Last accessed Jan 11, 2025

You also might like