Clean Architecture

Clean Architecture

You join a new organization and you are getting KT for the project maybe it is in MVC or MVVM or MVI and you just wonder what a specific class does and click through classes to check where is this being called, and then you feel clueless because you just don't understand what the hell is this, did this happen to any of you??

I present you the solution to this problem Clean Architecture.

What is Clean Architecture?

Clean Architecture is just another way to structure your code in different layers.

Here the flow of dependency is inwards meaning the innermost layer is not aware of the outside world and is not dependent on anything.

This Architecture is mainly based on isolating the classes as much as possible so that it is easily reusable in other contexts. Also, this makes our code easily testable.

Here is the image to represent that Entities are the area of focus here.

In Clean Architecture, we combine a whole lot of architectural ideas:

  • Screaming Architecture: meaning by just looking at your package structure and a filename a person should have a pretty good idea about the project.

  • Onion Architecture

  • UseCase driven Approach.

What is a UseCase?

A Use Case is generally defined as an action which your application performs like GetAgentByUuidUseCase

As you can clearly understand by just the filename that GetAgentByUuidUseCase gets a single agent by uuid from your data source.

class GetAgentByUuidUseCase @Inject constructor(
    private val repository: AgentRepository
) {
    operator fun invoke(uuid: String): Flow<Resource<Agent>> = flow {
        // do something
    }
}

You can have a different set of UseCases for a single feature and by using the same we did 2 things:

  • We separated the code from other files and this file will only have one thing to do so we followed the separation of concerns principle.

  • By just looking at the filename we can have a clear idea of what that class is going to be used for.

The added benefit is that we can easily attach this anywhere in our project.

The Package Structure

I have followed a package structure:

  • Data: responsible for holding data source information.

  • Domain: Business logic information.

  • Presentation: UI interaction.

Here you can imagine agent also as a separate module if you want your code to be separated into modules.

Conclusion

The basic idea here is to try to separate your code as much as possible by isolating the code and following the interface-based approach where we don't depend on a concrete implementation.

So that in future if we want to use a different service or different database it is easily replaceable.

Also keeping Entities as a centre of attraction and separating code using UseCases.

References

Check out the full android application which followed the Clean Architecture.

Video and Blog by Uncle Bob