Author Archives: yoelglus

MVP Anti-Patterns on Android

Some might argue that it doesn’t really matter the design pattern you choose, as long as you have a good separation of concern. I used to think so as well, but I noticed that in practice, the implementation of MVP in Android yields some interesting results. So when implemented correctly (I will explain what I mean later), it can be a handy way to separate logic from UI. I have seen many existing libraries that enable you to do MVP in Android like Mortar or Nucleus and it seems like the pattern of choice when developing on Android. In this post I won’t go into details on what is MVP, because many did that before me and you can probably find countless resources on this pattern online. What I will write about is some anti-patterns that I have seen when applying those patterns on the Android platform.

Using Android Components as the View

Often times, developers just use the Fragment/Activity as the view type of the generic presenter (e.g. interface MyPresenter<MyFragment>). I think that this is a very problematic step, for the following reasons:

  • Reducing testability: in order to unit test the presenter we need to mock the fragment or worse, create one. This usually involves Robolectric or instrumentation tests. I won’t repeat what I wrote in the previous blog post about the issues with Robolectric.
  • Tight Coupling: there is a very strong coupling between the presenter and the fragment it references. If we ever want to change the implementation of the view to be an Activity or a custom View we cannot do that without changing the presenter. This violates the Open/Closed Principle and makes our design rigid.
  • Implicit Interface: the Fragment will contain all the public methods that are part of his role as the view of this presenter as well as the fragment lifecycle methods and methods that are used by the Activity to send messages to the Fragment. If a developer wants to know what are the methods that are called from the presenter on the view, he/she needs to find all references to the fragment in the presenter and see which method it hits.

So my suggestion in this case is simple: create a MyView interface and implement it by MyFragment so that the presenter will be MyPresenter<MyView>. This removes all the issues listed above. There is a some boilerplate code involved in hooking the view to the presenter that you usually want to put a specific lifecycle events of the Fragment, but that can be achieved easily by creating a base fragment and base presenter.

The Case of the Sneaky MVVM

While working with a colleague, he told me that his Views have only one method which is setState(ViewState state); so essentially every time the state changes he invokes that method in the Fragment/Activity/Custom View and that view is in charge of doing a delta. You might think, what’s wrong with that? so a few things:

  • The God Object: first of all, he has this God object called the ViewState that can be changed without any clear indication in the interface. Some developer can come later and add some behavior to that object and then you end up with essentially a mish mash between MVVM and MVP.
  • Implicit Interface: again, the interface of the view is all about the state object, so I don’t know which behaviors does the view have by looking at this single method interface. It is hidden in the state object.
  • Sneaky MVVM: why do I call this the sneaky MVVM? because if you move the methods of the presenter to the state object you end up with something very similar to MVVM. Why is that a problem? people know design patterns, design patterns are tested, long living ways to design your code and having this made up version in your code can cause you a lot of grief if you scale your team. In large scale mobile apps with big teams, if a developer adopts this hybrid pattern, other developers might abuse it (see first bulletin – The God Object) and create a mess of responsibilities. It is hard enough to make sure that developers follow the existing pattern, so adding this custom pattern is even harder to implement.

The Huge Presenter

When people implement MVP it is to avoid having huge Activities/Fragments, better separation of concerns as well as better testability. In big and complex applications, if not combined with other patterns (I am a fan of Clean Architecture myself, and here is an example of how to implement it on Android) you end up with massive presenters. This, by the way, can happen also with MVVP or any other MV* pattern. These patterns are for UI, but if your business logic is very complex and big you should make sure you have some more abstractions to minimize the presenter.


MVP is a good pattern when you don’t fall into it’s traps on Android. I personally would prefer MVVM since the data binding library enables you to write less glue code and you are less likely to fall into anti-patterns as listed above.


TDD in Android using Robolectric

So I long time ago I started this project called MLBB – My Little Black Book. Sadly I had little time to actually work on it so it kind of died from natural causes… But that short experience and left me a bit confused. As much as I liked TDD applying these methodologies to the UI was a problem. Then I came across Robolectric and thought I found the silver bullet that I was looking for. Well, after trying it our a bit I noticed a few issues with it:


Running the unit tests was slow. Even though that they should be “just” JUnit tests, running the actual tests was slow. It kind of defies the purpose of the whole thing I guess. Though this is not the only reason to use Robolectric, I found it to be the biggest issue, because the rest of the advantages of this framework (running in a CI server for example) were irrelevant for my simple app as a single developer.

Implicit Bad Design

What do I mean by that? if you unit test your Fragments and Activities, you can end up putting logic in them because it is easy to unit test that, so why not? Doing so leaves you with huge Activities and Fragments without separation of concerns between UI and logic. I design pattern like MVVM in this case will be very beneficial.

Testing on Actual Devices it What I Really Wanted

The Android ecosystem is very fragmented, that it a known issue that every Android developer faces. Many things that work on one device might not work on another, even though that on paper they have the same OS version. Each vendor creates his own flavour of the Android OS and all kind of bugs are introduced (for example – multidex support in Galaxy S5 and S6 devices with a specific build). There is no real substitution for testing on actual device and those are tests that you can automate with the Instrumentation tests. Combining these tests with MVVM while covering the ViewModel with JUnit tests basically give you a similar cover that Robolectric does, but with a good separation of concerns and actual devices tests.

Though still in Beta, Android Data Bindings is in Beta now, but soon to be released and that will allow developers to use MVVM easily. My new approach that I am going to take with the MLBB project is as follows:

  1. Define the interface of the ViewModel.
  2. Implement the UI on a Stub ViewModel.
  3. Use TDD to implement the ViewModel with simple JUnit tests.

Using TDD for UI is a bit of an over kill in this case and doesn’t really give you much. You can still use TDD for the UI logic and application logic and just leave the actual rendering to the Fragments/Activities. These can be tested using Instrumentation tests to be run on the emulator or actual devices.

IoC and DI in Android using RoboGuice

Recently I started looking at Inversion of Control technique using Dependency Injection. In Java there is a great tool called Google-Guice. This tool is great for creating more testable, modular code. There is a porting to Google-Guice in Android called RoboGuice. This is what I am going to write about here.

Since we (Conduit Mobile) write a platform, our Android and iOS code needs to be designed properly. This means heavy use of design patterns and coding techniques most application developers seldom use (at least to my knowledge – no offence guys). This approach lead me to consider IoC. Since we want our modules to be interchangeable and testable, IoC is a good way to go. When coming to implement it, I came to a dilemma – should I implement it myself, or should I use an existing library. One of the biggest changeless in IoC in Android is the need of Context in many of the objects. RG solved it quite nicely with a neat annotation mechanism.

Contexts and Singletons

I wanted to create a singleton in my app that should depend on the Application Context. The problem is that this context is only available when the app starts. I wanted to avoid bootstrapping the object (some init function that receives a context as parameters). I also don’t like all the repetitive code of the Singleton design pattern. In RoboGuice they solved these stuff using the @ContextSingleton annotation. Sadly, the documentation is behind the code, but after playing with it, it is quite a nice way to implement this. All you need to do is this:

  1. Make your singleton with Context be annotated with the @ContextSingleton annotation.
  2. In the singleton, inject the context using the @Inject annotation.
  3. Make your Activity/Fragment extend the RoboActivity/Fragment.
  4. Inject the singleton using the @Inject annotation.

So, for example:

The RoboActivity will take care of injecting the activity context. You can specify the exact context you want by changing this code a bit and instead of injecting the context directly, use the @Inject on a constructor that accepts a context and get the application context. e.g:

RG also have tons of other cool features that can be useful (View/Resource injection). I plan on using RoboGuice and see how it turns out. Hope I’m not heading for a fall, but it seems better than implementing it all myself.

5 Things I Learned from the AQuery Source


This is a tribute to Paul Irish’s excellent video 10 Things I Learned from the jQuery Source. I think it is an great video and a good lesson for every developer – get to know the libraries you work with, and if they are open sources, get familiar with the source code. I already posted in this blog about Backbone.js and specifically on Backbone.js Views events. I could not accomplish that w/o getting my hands dirty in BB source code. Also, as Paul points out, this is a great way to learn new tricks. These open source projects are developed by some of the brilliant minds of the industry and there is a lot to learn from these guys.

So w/o further ado, let’s get down to business.

AQuery – you misspelled it

AQuery is (as taken from the AQuery Website): “inspired by jQuery, a javascript framework for web site, hence the name “Query”.” The difference is that AQuery is a library intended for Andoid developers and as such is written in Java.

I first came a cross this framework a couple of days ago when a colleague pointed it up to me. It immediately caught my attention and my team’s Android developer took it on a test drive the day after. We saw immediate results in performance boost and our code became much shorter and simpler. We only just started using it for image downloading and it is amazing. Till now, we implemented a whole “Download manager” component that became more and more complicated over time. With just a few lines of code we managed to make this component redundant and enjoy AQuery doing all the “heavy lifting”.

Inspired by Paul Irish’s video and approach, I started looking at the source code of AQuery, and I saw that not only they did an amazing library, the code is just equally great (thinking of it, it kinda make sense that a great library will be well written). This is how this blog post came to life. Hope you’ll enjoy reading it as much as I enjoyed writing it. I also hope that some of the things will give you new ideas about Android and Java programming.

1. Constants in Interfaces

This is an awesome way to avoid putting constants that you need to share across several classes in one class. I saw this in the AbstractAQuery class that implements the Constants interface. At first I thought: “What an odd way to name an interface”. Then it occurred to me that in Java, interfaces can contain constants, so why not use them this way instead of putting the constants in one of the classes and accessing them from all other classes?

It is important to note that I saw that the Constants Interfaces is considered bad practice (at least by this Stack Overflow post).

2. Generics and Object Creation

To extend AQuery, you need to write the following code:

class MyQuery extends AbstractAQuery<MyQuery> {…}
This, in turn, creates a new MyQuery object each time you use one of the “selector” function such as id. The reason this can be accomplished is the fact that you pass MyQuery as the generic param for the implementation. This is a nice way to implement extend ability.

3. Make it Green – Recycle

This is a very important practice that I already know from the adapters. When using adapters, one of the important parameters in the getView method is the convertView. This enables us to reuse an existing view (that is out of the scope of the screen) instead of creating a new one. The AQuery team also did an optimization that enables you to reuse the same AQuery object in an adapter.

4. Common Listener

Again, a nice trick they use to avoid creating multiple classes. The Common object implements a variety of listeners. This enables them to use the same invoke method for all the listeners. Also, it enables them to use that class as a file comparator, runnable and many other things.

5. Use of Weak References for Handlers

In the AJAX requests, the handlers are saved in a weak reference. This way, if the request is returned after the activity was destroyed, the activity will not leak. This is a very important practice to avoid leaking activities.

Backbone.js Views events

In my previous post I wrote about the Backbone.js library. When creating a view that contained several clickable areas and also anchor HTML elements I noticed that the anchor links did not work. Further investigation using a cool tool called Visual Event led me to the part of the code that interprets the view’s events object. In the Backbone.View constructor, there is a call for delegateEvents function. What this function actually does is go over the events object and use jQuery to bind the handlers to their relevant events. The thing is that in BB the events object has the ability to contain selectors e.g. ‘eventName .class-name’ : ‘eventHandler’. This little difference is quite big in terms of both performance and functionality. At the end of the delegateEvents function there are the following lines of code:

This little line of code makes all the difference. Instead of simply bind the event like he does when there is no selector, BB uses delegate. In the delegate documentation you see this simple explanation: “Attach a handler to one or more events for all elements that match the selector, now or in the future, based on a specific set of root elements.”. It is not by accident that I highlighted the “in the future” phrase. What it actually means is that he attaches a handler on the jQuery object, and when the event is triggered, it uses the selector to find the relevant element inside the element represented by the jQuery element. For example:

This will bind the tap event to all elements with the class=”class1″, and when the event is triggered, it will trigger it only on the inner elements with the class=”class2″. Let’s say that under a class1 element you have this element:

Tapping this element would just not work! You need to bind the tap event manually after the element is added to the view, so instead of writing this:

Which will cause this call:

You should call this:

You should know that there is subtle difference between these calls. In the first one I used “method” instead of this.eventHandler. The reason is that BB does not pass the function as is, but encapsulate it with its own bind method that allows it to pass a context to the method which is basically saying: when you run this handler function, set the “this” object to the one I specify. In the latter line of code, this.eventHandler will have the DOM element on which the event was triggered on as the context (“this” object). To overcome this “this” issue (sorry, couldn’t resist), you can use the jQuery.proxy function, in this case:

What we basically do is change the context of the eventHanler when called. Have a look on the proxy function implementation, pretty straight forward.

There is a lot to learn when looking inside the libraries code (as demonstrated in Paul Irish‘s highly recommended video: “10 things I learned from the jQuery source“). So don’t be afraid to look into these libraries and try not to consider them as a black box. I know I did.


I’ve been working with a framework called Backbone.js lately, and I really think that you should check it out.

From first glance, it looks that it doesn’t do much actually. But after working with it a day or two it immediately revealed its power. And to my opinion that power comes from its simplicity. It just organize your code in bits that you can reuse and manage with ease. I found that I write much better code faster.

Backbone.js (or in short BB) is an JS implementation of the MV(C) model. When writing a heavy JS app, BB is your friend. The reason that I put the “C” in parenthesis is that BB does not have that part of the MVC design pattern (the “Controller”).

Only thing I lack is a “Controller” in the MVC structure. But basically, I don’t miss him that much.

So try it out, very simple to learn and really improves your app.

Android WebView/Browser and Orange Rectangles

Wrote an answer to this on StackOverflow, but thought I should add it here as well.

First: The Problem

Orange rectangles appear when you select a link on a WebView/Browser. This is due to Android Touch Mode. What it basically does is let you know that the link is selected. This is an annoying problem and there are two ways to overcome this issue.

Therefore: The Solution

Two actually in this case:

  1. The Java/Native Approach: Call the webView.setFocusableInTouchMode(false). This only solves it half way and in the WebView where you run your HTML only. Also,  You should take into account though that this solution will make all text input boxes in your webpage unavailable.
  2. The CSS/Web Approach: Set the following css property: -webkit-tap-highlight-color:rgba(0,0,0,0); This will not cause the problem with the input boxes. But in this case you’ll need access to the HTML code you are running (though you can inject this to the HTML anyway).
That’s it,
Enjoy and till the next post…