Definition of Clean Architecture
Clean Architecture is a design pattern that uses "separation of layers," a technique used for many years by software engineers.
Uncle Bob initially promoted Clean Architecture (see http://cleancoder.com/products), focusing on the Java language, and it is implemented in other languages, such as Dart and Golang.
To follow this article, we must install NodeJS and our favorite IDE and understand Vue, Pinia, Typescript, and Tsyringe.
Clean Architecture is divided into four layers:
- Use Cases
- Controller and Delivery
The first layer that we need to understand is the entity layer. It is the layer where we put our interfaces, data type, enum, and everything else we know about the data.
We will use http://dummyjson.com/products to generate a product data sample in JSON.
The Repository layer is where the app communicates to the outside world. In this layer, we can put functions to call the RESTful API Service from the back-end app.
This is the layer where we apply logic to our data or state before the data goes to the delivery layer.
All data, state changes, and logic should be controlled from here.
The Delivery layer is for handling presentations or UI.
In Clean Architecture, the delivery layer focuses on getting data from the Use Case layer without making any changes. In this part, we are changing the state between the "loading," "empty," and "filled" states.
A simple if-else is sufficient for the toggling state.
There should be no data transformation in the delivery layer, it simply gets the data or invokes a function. All the state or data changes happen in the controller to get a clean UI.
Clean Architecture makes unit testing more accessible, as easy as mocking interfaces to get the desired data. We will show you how to test the repository and controller using Vitest. We use Vite as a Bundler, and Vitest fits it well. We will also be using Vitest-mock-extended for the bmocking interface.
First, we test the repository and will need to mock the ApiInterface.
We mock the ApiInterface and call the product repository using a mocked API to get the desired data. We will use Pinia, which already includes a built-in test for the controller.
It's easy enough to test when we use Clean Architecture because every layer has its importance.
Clean Architecture can be implemented in any language. It is the concept of "separation of layers" in coding. Generally, we implement this architecture in Java, but the same principles can be applied to front-end development.
Clean Architecture makes unit testing more accessible and pristine because all the layers are critical. The delivery layer is for the UI, including the controller, who handles UI logic, and the repository to obtain data and entities for storing all data types or interfaces.
You can see the complete code in this repo.
To learn more about our discussion on implementing Clean Architecture in Golang, click here.
Author: Andhika Satria Bagaskoro, Software Engineer Programmer