Clean Architecture is a software design philosophy that separates the software into many ring levels:
Each of the circle represents different layers of your software and must follow 2 important rules:
Dependency Rule: Dependencies can only go inwards. Basically, nothing in the inner circle can know any things of the outer circles.
Abstraction Rule: The more inward you go, the more abstraction the source code is. In another word, inner circles are business logic while outer circles are concrete implementation.
Like many other architecture patterns, the main purpose of Clean Architecture is separating concerns. So that:
The software will be independent of UI, frameworks, databases or any external dependencies
The source code is testable painlessly
The Clean Architecture can be applied to any type of software, based on the need, the number of circles can be varied as long as you still follow 2 important rules above.
The below figure showing my prefer layers for Android applications:
As you can see, we have 5 layers:
Entity: contains enterprise business logic or application business logic.
Data: provides the abstract interaction with data sources. Recommend using the Repository pattern in this layer.
Use Case: define all the use cases, interactions of users with the application.
Presentation: presents data to the UI, handle user interactions
Framework: implements the interactions with Android SDK and provides the detail implementation for the Data layer.
All right, we have enough bland boring theory 😂 It’s time to show you the code!
We’re gonna craft an application to show the public repositories on Github.
Below is the project structure that I will implement for the demo:
We’ll have 2 modules:
core: contains code for 2 layers Entity and **Usecases, Data **which is pure Kotlin, independent from Android SDK.
app: contains code for Presentation, Framework layer which depends on Android SDK and other external frameworks/libraries.
The relationship between 2 modules is visualized roughly as the diagram below:
I decided not to write every single class of the demo in this blog post (cause I’m lazy 😴).
So I’ll leave the link to Github repo with full implementation below and hope it can be descriptive enough for demo purpose 🤷♂️
Some important points of Clean Architecture:
Only outer layers can depend on inner layers
The inner layers are more abstract than outer layers
Numbers of layers should be varied base on the need of the project
Pros of using Clean Architecture:
Independent from UI and external framework (database, network,…)
Easy to add new features or maintain code
Cons of using Clean Architecture:
Extra code classes (but worth it!)
Not so shallow learning curve
Any feedback or comments are welcome as usual.
Thanks for reading and happy coding! 👨💻Written on March 15th, 2020 by Trinh Le