Article

There is no Clean Architecture

A Simpsons meme reads, I'll be honest with you, dev. There is no Clean Architecture.
A Simpsons meme reads, I'll be honest with you, dev. There is no Clean Architecture.

Clean Architecture has become such an essential topic in conversations about software development best practices that it's almost impossible to attend a technical interview or read a discussion thread without encountering it. It's a term that promises us a programming holy grail: separation, maintainability, and software that not only works well but is also a joy to work with.

When I first immersed myself in the world of Clean Architecture, I followed a path many engineers take. I searched YouTube, blogs, and so on. Like many others, my first point of reference was its original article on the Clean Code Blog.

When conversations about Clean Architecture start with the following diagram, we know we aren't heading in a good direction:

Clean Architecture diagram

This article focuses mainly on understanding what the elements presented in Uncle Bob's article refer to and contrasting them with what the book Clean Architecture tells us.

Following one of the examples we might find in these internet blogs, we encounter something like this:

- src
- - application
- - domain
- - infrastructure
- - interfaces

The problem is that this is merely an example. It doesn't mean your application, or every application, should look like this. In fact, Uncle Bob's own blog tells us:

Only Four Circles? No, the circles are schematic. You may find that you need more than just these four. There’s no rule that says you must always have just these four. However, The Dependency Rule always applies.

What is Clean Architecture, the book, about?

Contrary to what many associate with Clean Architecture, Robert C. Martin's book isn't limited to the four layers proposed in his famous article, nor does it focus on a rigid prescription for folder structure, aside from a brief discussion in the final chapter.

The book begins by establishing a framework for understanding "Architecture and Design" and warns about the risks of failing to invest in good design. Here, the author argues convincingly that maintenance and development costs can skyrocket over time if the architecture isn't sound from the beginning.

On programming paradigms, Martin takes us on a journey that emphasizes how software is usually a combination of several paradigms, rather than dogmatically choosing one over another.

Above all, the book is a treatise on principles, from SOLID principles to principles of Components, Architecture, and Layers, culminating in a discussion of common design patterns that serve what might be considered the heart of Clean Architecture: The Dependency Rule.

The Dependency Rule and the true essence of Clean Architecture

If I could briefly illustrate the essence of Clean Architecture in a code example, it would look something like this:

import React, { useReducer, useCallback, FormEvent } from "react";

// This interface represents the contract for the business logic layer.
// It defines the application's specific business rule for creating a user.
interface ICreateUserService {
  (data: { name: string; email: string }): Promise<void>;
}

// This hook represents the implementation of the use case.
// Ideally it should be in a separate file and could be improved
// by injecting dependencies that make the actual network requests,
// making it more adaptable to changes in external services.
function useCreateUserService(): ICreateUserService {
  const execute = useCallback(async ({ name, email }) => {
    // This is where you would normally interact with an external service,
    // such as an API. The API interaction should be extracted into a
    // separate module to follow the Dependency Inversion Principle.
    await new Promise((resolve) => setTimeout(resolve, 2000));
    console.debug(`User created: ${name} (${email})`);
  }, []);

  return execute;
}

// This represents the initial state of the form and should be self-explanatory.
const initialState = {
  name: "",
  email: "",
  loading: false,
};

type State = typeof initialState;

type Action = {
  type: "SET_NAME" | "SET_EMAIL" | "SET_LOADING" | "RESET_FORM";
  payload?: Partial<State>;
};

function reducer(state: State, action: Action): State {
  switch (action.type) {
    case "SET_NAME":
      return { ...state, name: action.payload!.name! };
    case "SET_EMAIL":
      return { ...state, email: action.payload!.email! };
    case "SET_LOADING":
      return { ...state, loading: action.payload!.loading! };
    case "RESET_FORM":
      return initialState;
    default:
      return state;
  }
}

// This component represents part of the UI layer.
// It should be responsible only for rendering and delegating user interactions
// to the use cases/business rules.
function UserForm({ createUser }: { createUser: ICreateUserService }) {
  const [state, dispatch] = useReducer(reducer, initialState);

  // This callback represents the user's interaction with the form.
  // It could be extracted into a separate component to follow the Single Responsibility Principle.
  const handleSubmit = useCallback(
    async (e: FormEvent) => {
      e.preventDefault();
      dispatch({ type: "SET_LOADING", payload: { loading: true } });
      try {
        await createUser({ name: state.name, email: state.email });
        dispatch({ type: "RESET_FORM" });
      } finally {
        dispatch({ type: "SET_LOADING", payload: { loading: false } });
      }
    },
    [createUser, state],
  );

  // The form elements should be extracted into separate components
  // to follow the Single Responsibility Principle.
  return (
    <form onSubmit={handleSubmit}>
      <input
        placeholder="name"
        type="text"
        value={state.name}
        onChange={(e) =>
          dispatch({ type: "SET_NAME", payload: { name: e.target.value } })
        }
      />
      <br />
      <input
        placeholder="email"
        type="email"
        value={state.email}
        onChange={(e) =>
          dispatch({ type: "SET_EMAIL", payload: { name: e.target.value } })
        }
      />
      <br />
      <button disabled={state.loading} type="submit">
        Create User
      </button>
    </form>
  );
}

// The App component is part of the outermost layer that composes the UI with the use cases.
export default function App() {
  const createUser = useCreateUserService();
  return <UserForm createUser={createUser} />;
}

The code satisfies Clean Architecture because of the following:

Separation of concerns: The code tries to separate responsibilities by dividing the logic into functions and components. The ICreateUserService interface defines a contract for user creation, and the useCreateUserService hook implements this logic. This is consistent with Clean Architecture principles that separate business rules from the UI.

The Dependency Rule: The Dependency Rule states that dependencies should point inward, from outer layers (such as the UI) toward inner layers (such as business logic and data). In the code provided, the UserForm component depends on ICreateUserService, which is a good example of dependency inversion and separation between the UI and business logic.

SOLID principles: The Dependency Inversion Principle (the D in SOLID) is present in the ICreateUserService interface.

In conclusion

As Eric Eliot's Composing Software says, composition is the essence of programming. The example we saw comes down to applying simple composition in React. All the principles and rules that make up architecture share the same origin as programming itself, and the Dependency Rule is just an alias for composition.

The design and architecture process isn't based on following an example or a guide to MVC, MVP, MVVM, and so on. It's based on understanding the principles and rules that give you tools and design patterns, and applying them in a way that fits your problem. There is no defined structure called "Clean Architecture" from Uncle Bob. Uncle Bob only gave us a guide to the principles and rules he uses to design software, which you can use to design yours.

Another reference I really like on separation into layers is Packages as layers, not groups.