Tag Archives: Patterns

Rebuilding a legacy app from scratch (III): Clean Architecture.

Once we have decided the features we want to have in our Minimum Viable Product version of the app, and before jumping straight away to start coding, we need to decide how are we going to design and architect the application.

Why we need to implement a good architecture? Because we want the code base of our application to be testable, scalable, robust, modular and maintainable, among other things.

Over the years a few architectures patterns has been defined and used by Software engineers for different platforms and systems but one of them that has gained lot of traction and popularity in the mobile community is the well known Clean Architecture.

 

What is Clean Architecture?

This pattern was defined by Uncle Bob and described in this blog post.

He summarise the main goals of a good Software Architecture:

  • Independent of Frameworks: We want to isolate the Android or iOS framework from our business / UI logic, making them testable and interchangeable.
  • Testable: This has been one of the traditional issues when designing the testing strategy of our apps, it was difficult to test a module that has many external dependencies, like the Android SDK.
  • Independent of UI: We want to have our UI independent from our business logic, this way the last one can be unit tested without having to depend on UI or Integration tests.
  • Independent of Database: The source of data must be isolated from the rest of layers of the app, this way we can change this source without affecting the logic of the app.
  • Independent of any external agency: The business logic doesn’t depend on any external factor.

 

An Android approach to Clean Architecture

So for our Android implementation of the Clean Architecture we are going to follow the design described by Fernando Cejas in one of his great blog post.

We are going to identify three main layers in the code base: Presentation layer, Domain layer and Data layer.

 

Presentation layer

We are going to use  the Model-View-Presenter (MVP) pattern to implement this layer. I will explain briefly this presentation pattern but you can see a more detailed explanation in my introductory article here.

Basically we are going to have a View entity,  where we implement the Activities, Fragments and Views. These are what we call passive views, what means that they are totally dumb and have zero presentation or business logic. They just display information in the screen under the direction or the Presenter and dispatch events back to this one, like user actions.

Then we have the Presenter that as mentioned previously contains all the presentation logic and is acting as a bridge between the View and the Model layer. This entity should not have any Android dependency, but it knows how to respond to user actions and how to retrieve the information or data that is required to display in the view.

And finally we will have the Model layer that will contain the bridge and adapter classes accessing the Domain layer of our architecture.

 

Domain Layer

It’s going to contain all the business logic of our app. Once again there shouldn’t be any Android dependency in this layer. In here we will implement what we call Interactors, which basically are Use Cases.

For example, if we look into the MadridBus application, we will see that one use case is to get the list and information of all the bus lines in the city. This logic will be implemented in one Interactor and it will be used by the Presenter of the Line List View.

So when the user open the line list screen, the View is going to tell the Presenter that it has been loaded, the Presenter knows then knows that have to retrieve the line list, so it’s going to instantiate and use the GetLineListInteractor, which is going to access the Data Layer to get the list of lines. When the data set is returned the Presenter knows calls the View and tell it to display this information in the right way.

 

Data Layer

In this layer is where all the data of the application is stored and processed. This layer is responsible of providing the mechanisms to retrieve the data that the app needs. The Interactors will be calling the API of the data layer so they can retrieve this data to the Presenters.

We want to make the data source totally agnostic for the rest of the different layers of the app. This means that the Interactors doesn’t know from where the Data layer is extracting the information, they will just call the interface of the API exported following the Repository Pattern.

Screen Shot 2017-04-27 at 22.47.21

From Hannes Dorfmann blog post 

 

For example, in the app we are going to have two sources of data, the first one will be the Cloud, from the public transport agency data service. Then we will have the local database, where we will save the data taken from the cloud, so the next time when the GetLineListInteractor call the Repository to get the list of lines, if this exist in the local database, it will retrieve from there, and if not it will retrieve it from the cloud.

To read more about the repository pattern check out this great blog post from Hannes Dorfmann.

 

The project structure

One importante aspect when designing our code base which is dependent on the architecture of the app is the structure of the different modules and how are they grouped in the project.

As Uncle Bob says, this is like a blue print of the application. Looking at the project structure should give us an idea of what this system is about.

Screen Shot 2017-04-23 at 00.27.36

As we can see in the screen shot, the project has four main module groups: DI, Domain, Model and UI.

In DI we have all Dagger 2 dependency injections helpers.

Domain as we have mentioned before contains the business logic, interactors, network modules, rules, etc.

In Model basically we have Pojos and data classes.

Finally in UI we have all the Presentation layer modules, like Activities, Presenters, etc.

With this project structure we can easily find and navigate to a specific feature or functionality of the app, either the UI part, the Domain or the Data component of it.

 

Conclusion

A good architecture is the blueprint for our project, it will guide our implementation and will keep the maintainability, testability, cohesion and modularity of the project.

Clean Architecture is not the silver bullet nor the only way to design our apps, but has proved to be one of the best solutions.

We will be following this pattern in the MadridBus source code implementation that you check out in Github here.

Tagged , , , ,

An introduction to MVVM pattern on Android with the Data Binding Library

In a previous post we made a brief introduction to the MVP architectural pattern, describing how it help us to create a much cleaner, testable and modular source code for our application.

In this post we are going to talk about the MVVM pattern and explain how using the new Android Data Binding Library we can achieve the same level of modularity and separation of concerns but one step ahead, making the data binding with the UI layer less verbose and straightforward, which will produce source code less prone to errors and bugs.

 

What is MVVM?

Model-View-ViewModel is a variation of the MVC and MVP patterns initially described and implemented by Microsoft to be used on the .NET platform, specifically with WPF and Silverlight technologies that makes use of the XAML language to implement User Interfaces.

In the Microsoft ecosystem one of the main advantages of this pattern is that the designers can implement the View working completely independent of developers using Blend, which is an amazing UI IDE. Then developers can focus only on the ViewModel and Model and wiring everything with the Binding functionality. This in Android is much more difficult as the UI designer tools are not powerful enough.

Screen Shot 2015-12-05 at 10.59.55

Like in the MVP pattern we separate and architect our code in three well defined layers.

The View defines the pure user interface and it has no logic at all except any related only to the UI. If we focus on the Android platform in this layer we would have Activities, Fragments, Dialogs, Views, etc. As we saw in the MVP post these entities will implement an interface that will be use as bridge with the ViewModel layer.

The Model integrates our data strategy, backend support, pojos, and generally speaking what we all know as business logic. These will be implemented via Interactors which defines uses cases of the domain logic.

And finally we have the ViewModel which differentiate this patterns from others. Conceptually this layer is in charge of the same logic as the Presenter in the MVP, which is acting as a facade and brain between our data model and the user interface.

It will be able to identify the application status and display or fetch data and information using the View and the Model. The ViewModel knows how and where to display the information in the user interface. Also it knows where  and how to get this information from the Model.

But the main difference is how this data are passed from the model to the View, which in the VM happen using a mechanism called Data Binding.

 

What is Data Binding?

Data Binding is a mechanism where a view component is linked to a data entity of the ViewModel without having to implement specific code to transform or assign this data to the visual component. We can send and receive commands and events and also connect data source to the component. In Android this magic happen thanks to the recently added Data Binding Library.

As we can see, one of the main advantages of using Data Binding is the time we save due the amount of code that we don’t have to implement to connect the data and the view and hence the possible bugs and code defects that we will avoid.

 

Implementing Data Binding on Android

First thing we need to use the Android Plugin for Gradle version 1.5.0-alpha1 or higher.

classpath 'com.android.tools.build:gradle:1.5.0'

Then we configure the app to use the data binding feature in the build.grade file.

dataBinding {
enabled = true
}

Now we need to add the data binding to the component that is going to display the data that we need. For this example we will use two TextView which are going to display a user name and email that we will fetch from a web service using Retrofit. Once we have the response from the server, this info will be automatically updated on the view.

So let’s add the binding code in the layout of our view, in this case we are adding a reference to the pojo class that contains the data that we are binding and that will fill up with the response of our server request. Also we are setting the TextView wit the field of the that contains the specific user name and email:

<layout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" tools:context="com.quoders.apps.androidbootstrap.mvvm.MvvmExampleFragment">

<data>
<variable name="commentItem" type="com.quoders.apps.androidbootstrap.rest.model.CommentItem"/>
</data>

<TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:text="@{commentItem.name}" android:layout_marginTop="15dp"/>

<TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:text="@{commentItem.email}" android:layout_marginTop="5dp"/>
</layout>

Next we need to initialise the binding objet in the Activity or Fragment. Note that the FragmentMvvmExampleBinding is created automatically by Android Studio:


FragmentMvvmExampleBinding mBinding = DataBindingUtil.setContentView(getActivity(), R.layout.fragment_mvvm_example);

And finally when we have the response from the HTTP request we do the binding with the pojo that contains the data to bind:


mBinding.setCommentItem(mComentItem);

As you can see in this example, the UI component is update on demand when we have the server response data. Although this feature is pretty cool, what makes data binding really powerful is the ability to update the UI component automatically each time that the status of the bind object changes. We accomplish this extending our pojo data class from the BaseObservable class that the Data Binding library provides and setting the fields as observables. In our example it would look  like this:

public class CommentItem extends BaseObservable {

@Expose
private String name;
@Expose
private String email;

@Bindable
public String getName() {
return name;
}

@Bindable
public String getEmail() {
return email;
}
}

There are multiple possibilities like binding collections, resources, automatic setters, etc… But all this due its extension will be the topic of another post!

You can find the source code with this example here in the FragmentMvvmExample. To check out how to implement the division of layers on MVP / MVVM have a look to my previous post.

As usual all comments, suggestions or critics are more than welcome, please leave your comments!

 

Tagged , , ,

A brief introduction to a cleaner Android architecture: The MVP pattern

As the Android platform has been maturing, developers found that the standard approach to organise the architecture and design of the application code wasn’t the best at all. Usually we ended up having a massive monolithic module, an Activity or a Fragment, containing business and UI logic, creating an unmaintainable and untestable messy project.

Google itself haven’t provided so far a good practice guideline or code examples showing a modular and decoupled approach that implements any of the well known and widely used design patterns, like for example MVC which is encouraged by default on the iOS platform or the common MVVM in Microsoft environments.

One of the most common pattern that the community of Android developers has been using for a while and that has got lot of attention is the Model View Presenter (MVP) pattern and we will focus on it on this post. We will not go through a deep academic description of the pattern but we will focus on the advantages and practical use of it. For an awesome analysis of the MVP and other patterns take a look at this classic post from Martin Fowler about GUI architecture.

So what’s MVP?

18289

Basically MVP is an architectural design pattern that divides our application code in three entities in order to achieve a modular design, implementing the separation of concerns concept, allows an easier implementation of unit tests and making possible to reuse and replace modules either of our UI, data or business layer.

MVP is an evolution of MVC and it has multiple variants and implementations. There has been a lot of conversations and debate about the best and proper way to adopt it on Android. I’m going to expone my way which I have been using in a couple of projects and I reckon works better for me. Of course it doesn’t mean is the best or only one that works on Android, so please leave any comment and suggestions if you find any area of improvement.

Ok so let’s see who is who in this approach.

The View

This entity is going to include the visual part of our app, it is only the UI and it will not have any logic or knowledge of the data displayed. The View doesn’t know anything about the business logic or how to get the data it has to show to the user.

Activities, Fragments, Dialogs, etc… would be included in this category. This elements will contain only initialisation and display functionalities of the visual components and elements to display information to the user. It will not contain any functional or business logic like access to database or web server for example.

This module (Activity, Fragment, etc) exports an interface that will be used by the Presenter, which is responsible and have the knowledge and logic about how, when and what to show in the View. This interface will have methods like “showProgressBar”, “showLoginErrorMessage” or “launchSignupActivity”. Here is an example:

public interface WelcomeView {

    void launchHomeActivity();
    void LaunchSignupActivity();
    void closeActivity();

    void setWrongUsernameError();
    void setWrongPasswordError();

    void showLoginErrorAlertDialog();
}

The Presenter

As we mentioned before, this entity is going to have all the logic and knowledge about what, how and when to display in the user interface. It will be responsible of capture events raised by the user when interacting with the UI and perform any action.

The presenter also acts as a bridge between the View and the Model fetching any data needed from the data layer, making any transformation and display this info to the user on the View.
This entity ideally shouldn’t have any dependency of the Android SDK such us Context or Activity references.

The Activity will have a reference to the Presenter interface and it will use it to communicate any event occurred on the View, like the user tap on a button or the user enter any data in a TextView and then it will decide what to do in reaction of that event.

Here is an example of a Presenter interface:

public interface WelcomePresenter {
    void onCreateAccountClick();
    void onActivityResultCalled(int requestCode, int result);
    void onLoginClick();
}

So for example let’s say that if the user tap on a Logout button, the View call the exported method “onLogoutClick” of the Presenter interface. Then the it knows what interactor of the Model layer needs to invoke to perform a Logout action on the app.

Once the log out success callback has been received, the Presenter will perform any action on the View, for example closing the Activity and displaying a home screen Activity.

The Model

In this entity we will include the “interactors” (use cases of our business logic) that will perform and manage any business layer logic and data access, like fetching data from our web service, accessing the database, etc.

Once we have that piece of data the interactor will send it back to the Presenter and this will decide what to do with this data and how to show it to the View as we saw in the previous point.

Here an example of an implementation of an interactor:

public class WelcomeInteractorImpl implements WelcomeInteractor {

    private WelcomeInteractorListener   mListener;

    public WelcomeInteractorImpl(WelcomeInteractorListener listener) {
        this.mListener = listener;
    }

    @Override
    public void loginWithUserName(String username, String password) {

        ParseUser.logInInBackground(username, password, new LogInCallback() {
            public void done(ParseUser user, ParseException e) {
                if (mListener != null) {
                    if (user != null) {
                        mListener.onLoginSuccessful();
                    }
                    else {
                        mListener.onLoginError(e);
                    }
                }
            }
        });
    }
}

Summary

So this is a very brief summary of what is MVP and how to use it on Android to achieve a cleaner, modular and testable source code. This is just an interpretation of the pattern and is not a silver bullet or the perfect solution for our apps, so any comments or critics are more than welcome!

To see an example of this implementation you can take a look to one of my open source experimental apps “Treepolis”. Is still an in progress project and you can find it here in Github
To see a practical example of the pattern used for the Welcome screen and login functionality check this folder.

Tagged , , ,