Android clean architecture

Use clean architecture in android application

By Subash Adhikari · · 5 min read

Share on X


One of the main reasons we build software is to meet a business goal. Whether it's a simple shopping list app or a large banking application, it exists to solve a problem. As the software grows, it has to cope with changing business requirements. Well written software can take on those changes quickly without breaking other parts of the application. Over time, lots of design patterns and architectures have emerged to help with this. Whichever one you pick, the end goal is the same. You want software that solves the business problem and is also robust, maintainable, testable and flexible enough to keep up with change.

Diagram of three layers: Presentation (Model View Presenter), Domain (regular Java objects) and Data (Repository pattern), joined by interactors and boundaries

The idea behind clean architecture is quite simple. It encourages you to build software that is independent of frameworks, independent of the database, independent of the user interface, and easy to test. You can picture it as an onion with 4 layers, where each layer is a component of the software. The innermost layer is about data and deals with getting the data the software needs to run. The layer above it holds all the business logic. It gets data from the data layer and does whatever logic is needed. The presentation layer is the bridge between the UI layer and the business layer. The UI layer is where all the framework specific stuff happens. It has the Android components and fragments, and it builds the user interface and renders the UI components. The important rule is that an outer layer depends on the layer right below it, never the other way around.

In practice the software is split into 3 tiers: the data layer, the domain layer and the presentation layer. The data layer deals with where the data comes from, and the presentation layer deals with how the user interface is shown. The business layer in the middle has no idea where the data comes from or how the UI is rendered. That keeps the business logic independent of both data and presentation. Data mappers are used to pass data between the layers.

Clean Architecture concentric circles: UI, Presenters, Use Cases and Entities, with dependencies pointing inward

Implementation#

Since the core of the software is the business requirement it fulfils, the project is organised into components named after those requirements. In the example movie app, one requirement is to show a list of upcoming movies. The code below shows how to do that with clean architecture. Everything needed for this feature lives in a component called upcomingmovies.

Business layer

java
/// Movie.java
/// Representation of Movie in business layer
public class Movie {
  private int id;
  private String title;
  private double rating;
}
 
/// MovieRepository.java
/// Our business rule will depend on this contract for data
public interface MovieRepository {
  List<Movie> getNowPlayingMovies();
}
 
/// Business logic to get the upcoming movies
public class GetUpcomingMoviesUseCase {
 
  private MovieRepository repository;
 
  GetUpcomingMoviesUseCase(MovieRepository repository) {
    this.repository = repository;
  }
 
  public List<Movie> executeUseCase() {
    return repository.getNowPlayingMovies();
  }
}

Here executeUseCase is really simple. In a real application the use case would usually be more involved.

Data Layer

The data layer is where we fetch data from storage. That storage can be anything, anywhere, as long as it implements MovieRepository, which is how the business layer talks to the data layer.

java
/// MovieEntity.java
/// Representation of Movie in business layer
/// This can be specific to where and how the data is stored
public class MovieEntity {
  private int id;
  private String title;
  private double rating;
}
 
/// MovieStore.java
interface MovieStore {
  List<MovieEntity> getNowPlayingMoviesFromStorage();
}
 
/// APIMovieStore.java
public class APIMovieStore implements MovieStore {
  public List<MovieEntity> getNowPlayingMoviesFromStorage() {
    // get the movie list from internet
  }
}
 
/// SQLMovieStore.java
public class SQLMovieStore implements MovieStore {
  public List<MovieEntity> getNowPlayingMoviesFromStorage() {
    // get the movie list from SQL database
  }
}
 
/// MovieDataRepository
public class MovieDataRepository implements MovieRepository {
 
  // this can either be SQLMovieStore or APIMovieStore
  private MovieStore movieStore;
 
  public List<Movie> getNowPlayingMovies() {
    List<MovieEntity> movieEntityList = movieStore.getNowPlayingMoviesFromStorage();
 
    // MoiveMapper transforms MovieEntity to Movie so it can be used in business layer
    List<Movie> movieList = MovieMapper.transform(movieEntityList);
 
    return movieList;
  }
}

This data layer implements MovieRepository from the domain layer. MovieDataRepository gets its data from the MovieDataStore. Notice that it doesn't really matter where the data comes from. In this example it could come from SQL or from a web API. Either way, the business layer only gets the data it needs. All the complexity of where and how the data is fetched stays inside the data layer. MovieEntity is mapped to Movie by a transformer before it's handed to the business layer. Entity objects live only in the data layer and never leave it.

Presentation layer

Now that we can get data from the data layer and run our business logic in the domain layer, it's time to put it on the screen.

java
/// MovieModel.java
/// Representation of Movie in presentation layer
public class MovieModel {
  private int id;
  private String title;
  private double rating;
}
 
/// NowPlayingView.java
/// Contract defined to force the view logic
public interface NowPlayingView {
  void renderNowPlayingMovies();
}
 
/// NowPlayingPresenter.java
/// This should not have any framework related code
public class NowPlayingMoviesPresenter {
  private NowPlayingView view;
  private GetNowPlayingUseCase usecase;
 
  public NowPlayingMoviesPresenter(GetNowPlayingUseCase usecase) {
    this.usecase = usecase;
  }
 
  void setView(NowPlayingView view) {
    this.view = view;
  }
 
  void initialize() {
    List<Movie> movies = usecase.executeUseCase();
 
    /// Transform Movie to MovieModel
    List<MovieModel> movieModelList = Mapper.transform(movies);
 
    // ask the view to render movies
    this.view.renderNowPlayingMovies(movieModelList);
  }
}
 
/// NowPlayingFragment.java
/// This view is specific to android
public class NowPlayingFragment implements NowPlayingView {
 
  @Inject NowPlayingPresenter presenter;
 
  @override void onViewCreated(/*params*/) {
    presenter.setView(this);
    presenter.initialize();
  }
 
  @Override void renderNowPlayingMovies(List<MovieModel> movieModelList) {
    // render the movieModelList in the view
  }
}

In the presentation layer, the Presenter holds the logic for talking to the business layer. It also talks to the View and passes it the data it needs. But it has no framework specific logic. So if the requirements change later and we need a web app that does the same thing, we can just create a new NowPlayingView for the web that shows now playing movies in the browser.

Conclusion#

For a non trivial application this means a lot of code to write, and it might not be worth the hassle if you're absolutely sure the requirements won't change. For medium to large projects, though, I highly recommend this architecture. I'll soon write another post where we update the UseCase to use Observables from RxJava. That will let these use cases run on a background thread without blocking the main thread. Google also recently released Lifecycle aware components, ViewModel and LiveData as part of the new Android architecture components. It'll be interesting to see where those fit into clean architecture.

Useful resources#

Android Clean Architecture Github project

Architecturing android.. The clean way

Clean Architecture Book

Android and Architecture


Thanks for reading. You can also follow along on X or with RSS.