Skip to main content

Second level of implementing clean architecture

Clean architecture is a term that was coined by Uncle Bob Martin which describe the way we should write our software, as I know, in clean architecture we need to break our software into two parts, core business logic and the framework/infrastructure, our software needs to have obvious API of the business core and also we need to abstract how the infrastructure interact with our business core.

Some of the purposes of Clean Architecture are making the business core become obvious, decouple them from the input and the output, and can easily test our business core easily because we can test them in isolation, thus make us confident with our code.

But, in implementation, if we implement this in a strict mode, this can slow down the development time, especially if our application is small. This can be solved by using an implementation that is looser. I call this second level, while the first level is implementing in a strict mode.

In strict mode, not only we need to make the core business API obvious, but we also need to write our business core code as loose as possible to the framework, this can be achieved by abstracting the dependencies that our business core use, and on the framework side, we write the implementation, this way we can switch the implementation easily, even we can switch the framework altogether.

For implementing the second level, we only extract the core business API and make that API the only way for the framework to communicate with our business core. For the business core dependency, we can couple them with the framework, this way, our development time will be faster because there won't be too much boilerplate code.

Here, I will give some silly examples from an application that I wrote using Laravel framework, just so you can get the overall idea. The business core of this application is library, with this application, we can manage a library, like, add records when a user borrows book, etc.



As you can see above, I move all business core related code into Domain folder, and the public API for the business core are in UseCases folder, just by seeing that, you can know what the application is all about.



As you can see above, one of the use case class depends on the user repository class, we can typehint the class directly instead of using interface as typehint in the constructor.


 
Now, in the controller, we can directly inject the use case in, as you can see above. 

By extracting the core business logic in UseCase class like above, you can easily unit test them without actually using any HTTP server or sending HTTP requests. 

In conclusion, by implementing Clean Architecture this way, we can get the benefit of Clean Architecture, such as obvious public API of our core business, easiness of testing of business core related code, and faster development time cause we don't need to think about too much abstraction.

Comments