Single Responsibility1, Beware the Share2, Boyscout Rule3. These are some conventions that guide good practice in software development and I believe naming can benefit from these ideas and other practices. This blog post will discuss class naming using Model View Presenter as the example and show you one change you can do to make your code cleaner and more readable.

MVP4 is being used as one example of a design pattern that requires thoughtful naming, this article doesn’t give you direction for what your Model, View or Presenter should do as behaviour, but we can all agree that you usually have an interface for each of these ideas. Infact the main benefits of this article can be taken to naming any grouping of classes and you can reinterpret these ideas for other class naming.

Many people try to come up with a great name all at once. This is hard and rarely works well. The problem is that naming is design: it is picking the correct place for each thing and creating the right abstraction.

This quote comes from an amazing eight part blog post5 that talks about how naming can go through seven stages. As a TLDR; The stages include Missing name, Nonsense naming, Honest naming, Honest and Complete, Does the Right Thing, Intent, Domain Abstracted naming. I believe many people change variable names and go through the stages as discussed maybe not hitting every stage and maybe not getting to the end, but still, variables are renamed often. If these names move towards the right side of this scale, this is movement towards more expressive and readable code.

I want to skip variable naming and move straight on to class naming. Variables get renamed an order of magnitude more often than Classes get renamed. There seems to be a bigger barrier to class renaming, in that it will likely touch more code, affect more people, ruffle more feathers, and so it is done less often. Let’s drop this as an excuse not to strive for clean code and accept class naming as fair game.

Consider a class that implements the interface TweetsView, one bad way of naming this implementer is like this TweetsViewImpl implements TweetsView. Impl?? Impl!! Naming an implementation is an important opportunity to convey some meaning about what that specific implementation does. It’s lazy to just go with Impl and not think about what your class does.

My interface name describes the behaviour of my class. I can’t think of anything more to add to that, I’ll just use Impl.

Next logical step people usually take is, they know Impl is bad naming, but still can’t think of a name because the interface TweetsView seems exactly the right name; its a view of the tweets. They avoid the Impl code smell with something just as bad: DefaultTweetsView, SimpleTweetsView or flip it round TweetsView implements ITweetsView (this just moves the problem rather than resolves it, but a good hint of what is to come 🙂 ).

You want your classes to be named after the behaviour they exhibit, following the Single Responsibility Principle you should know what this responsibility/behaviour is.

There are two solutions here:

Only 1 implementer of the interface? Get rid of the interface! Over abstraction is unnecessary and confusing.

Understand the problem space and name explicitly according to behaviour TrendingTweetsView implements TweetsView

Now thinking about class naming and interfaces from another perspective. If we are using MVP and have an interface for TweetsModel, TweetsView, TweetsPresenter. Then these three interfaces are actually intertwined and should be considering as a system. For example, someone new to the code base, seeing a class implementing TweetsView could think this is just some type of custom view (not MVP), they could then see the other code implementing TweetsModel and still consider this as some other pattern, it’s not until they also notice implements TweetsPresenter that they’ll put the three together. It would be nice if we could make this grouping explicit in the code, lets see an example.

Awesome, we have declared our triad of interfaces under one common name. This fixes the problem of understanding the system. Any legacy developer reading this code or reading one of the implementations can see this interface comes from this triad and that it’s clear intention is to be used in the MVP pattern.

When we implement the triad of interfaces it further backs up the knowledge that this class is being used in the MVP pattern. Further we have resolved our Impl naming issue. We can have our view of the tweets called TweetsView and this implements an MVP View of Tweets; implements TweetsMvp.View.

This wouldn’t be possible if you just called the individual interfaces Model, View and Presenter. Firstly you usually have multiple MVP interfaces in a codebase and so such generic naming would get very confusing very quickly. Secondly on Android View is already used for the UI system and so one of the two View classes/interfaces would have to be fully qualified which adds noise to the code.

I hope you find the grouping concept useful even if my poor textual explanation doesn’t get you, then the code example should make it obvious.

Always remember to consider your systems as a whole, what parts of the system are interconnected and should these relationships be made explicit. Naming plays an important role in your codebase and getting it right is hard. If ever stuck, think where you are up to on the seven stages of naming; missing name, nonsense naming, honest naming, honest and complete, does the right thing, intent, domain abstracted and what other entities changing this name might effect.

It’s easy to get comfortable with boilerplate setup code, so much so that we gloss over the finer details. I’ve experienced this with LayoutInflater (which coverts an XML layout file into corresponding ViewGroups and Widgets) and the way it inflates Views inside Fragment’s onCreateView() method. Upon looking for clarification in Google documentation and discussion on the rest of the web, I noticed that many others were not only unsure of the specifics of LayoutInflater’s inflate() method, but were completely misusing it.

Much of the confusion may come from Google’s vague documentation in regards to attachToRoot, the optional third parameter of the inflate() method.

Whether the inflated hierarchy should be attached to the root parameter? If false, root is only used to create the correct subclass of LayoutParams for the root view of the XML.

Maybe the confusion comes from a statement that ends in a question mark?

The general gist is this: If attachToRoot is set to true, then the layout file specified in the first parameter is inflated and attached to the ViewGroup specified in the second parameter.

Then the method returns this combined View, with the ViewGroup as the root. When attachToRoot is false, the layout file from the first parameter is inflated and returned as a View. The root of the returned View would simply be the root specified in the layout file. In either case, the ViewGroup’s LayoutParams are needed to correctly size and position the View created from the layout file.

Passing in true for attachToRoot results in a layout file’s inflated View being added to the ViewGroup right on the spot. Passing in false for attachToRoot means that the View created from the layout file will get added to the ViewGroup in some other way.

Let’s break down both scenarios with plenty of examples so we can better understand.

attachToRoot Set to True

Imagine we specified a button in an XML layout file with its layout width and layout height set to match_parent.

We now want to programmatically add this Button to a LinearLayout inside of a Fragment or Activity. If our LinearLayout is already a member variable, mLinearLayout, we can simply add the button with the following:

inflater.inflate(R.layout.custom_button, mLinearLayout, true);

We specified that we want to inflate the Button from its layout resource file; we then tell the LayoutInflater that we want to attach it to mLinearLayout. Our layout parameters are honored because we know the Button gets added to a LinearLayout. The Button’s layout params type should be LinearLayout.LayoutParams.

The following would also be equivalent. LayoutInflater’s two parameter inflate() method automatically sets attachToRoot to true for us.

inflater.inflate(R.layout.custom_button, mLinearLayout);

Another appropriate use of passing true for attachToRoot is a custom View. Let’s look at an example where a layout file uses a <merge> tag for its root. Using a <merge> tag signifies that the layout file allows for flexibility in terms of the type of root ViewGroup it may have.

This is a perfect use for a trueattachToRoot parameter. The layout file does not have a root ViewGroup in this example, so we specify our custom LinearLayout to be its root. If our layout file had a FrameLayout as its root instead of <merge>, the FrameLayout and its children would inflate as normal. Then the FrameLayout and children would get added to the LinearLayout, leaving the LinearLayout as the root ViewGroup containing the FrameLayout and children.

attachToRoot Set to False

Let’s take a look at when you would want to set attachToRoot to false. In this scenario, the View specified in the first parameter of inflate() is not attached to the ViewGroup in the second parameter at this point in time.

Recall our Button example from earlier, where we want to attach a custom Button from a layout file to mLinearLayout. We can still attach our Button to mLinearLayout by passing in false for attachToRoot—we just manually add it ourselves afterward.

These two lines of code are equivalent to what we wrote earlier in one line of code when we passed in true for attachToRoot. By passing in false, we say that we do not want to attach our View to the root ViewGroup just yet. We are saying that it will happen at some other point in time. In this example, the other point in time is simply the addView() method used immediately below inflation.

The falseattachToRoot example requires a bit more work when we manually add the View to a ViewGroup. Adding our Button to our LinearLayout was more convenient with one line of code when attachToRoot was true. Let’s look at some scenarios that absolutely require attachToRoot to be false.

A RecyclerView’s children should be inflated with attachToRoot passed in as false. The child views are inflated in onCreateViewHolder().

RecyclerViews, not us, are responsible for determining when to inflate and present its child Views. The attachToRoot parameter should be false anytime we are not responsible for adding a View to a ViewGroup.

When inflating and returning a Fragment’s View in onCreateView(), be sure to pass in false for attachToRoot. If you pass in true, you will get an IllegalStateException because the specified child already has a parent. You should have specified where your Fragment’s view will be placed back in your Activity. It is the FragmentManager’s job to add, remove and replace Fragments.

The root_viewGroup container that will hold your Fragment in your Activity is the ViewGroup parameter given to you in onCreateView() in your Fragment. It’s also the ViewGroup you pass into LayoutInflater.inflate(). The FragmentManager will handle attaching your Fragment’s View to this ViewGroup, however. You do not want to attach it twice. Set attachToRoot to false.

Why are we given our Fragment’s parent ViewGroup in the first place if we don’t want to attach it in onCreateView()? Why does the inflate() method request a root ViewGroup?

It turns out that even when we are not immediately adding our newly inflated View to its parent ViewGroup, we should still use the parent’s LayoutParams in order for the new View to determine its size and position whenever it is eventually attached.

You are bound to run into some poor advice about LayoutInflater on the web. Some people will advise you to pass in null for the root ViewGroup if you are going to pass in false for attachToRoot. However, if the parent is available, you should pass it in.

Lint will now warn you not to pass in null for root. Your app won’t crash in this scenario, but it can misbehave. When your child View doesn’t know the correct LayoutParams for its root ViewGroup, it will try to determine them on its own using generateDefaultLayoutParams.

These default LayoutParams might not be what you desired. The LayoutParams that you specified in XML will get ignored. We might have specified that our child View should match the width of our parent View, but ended up with our parent View wrapping its own content and ending up much smaller than we expected.

There are a few scenarios in which you will not have a root ViewGroup to pass into inflate(). When creating a custom View for an AlertDialog, you do not yet have access to its parent.

In this case, it is okay to pass in null for the root ViewGroup. It turns out that the AlertDialog would override any LayoutParams to match_parent anyway. However, the general rule of thumb is to pass in the parent if you’re able to do so.

Avoiding Crashes, Misbehaviors and Misunderstandings

Hopefully this post helps you avoid crashes, misbehaviors and misunderstandings when using LayoutInflater. Here are some key takeaways for different uses in certain circumstances:

If you have a parent to pass into the root ViewGroup parameter, do so.

Try to avoid passing in null for the root ViewGroup.

Pass in false for the attachToRoot parameter when we are not the ones responsible for attaching our layout file’s View to its root ViewGroup.

Do not pass in true for a View that has already been attached to a ViewGroup.

上面这种启动方式，在启动完Service后，这个Service就开始在后台运行了，同时，也与启动它的Activity失去了联系，因为不能通过ServiceTest service = new ServiceTest()的方式启动Service，因而我们的Activity中不能获取到ServiceTest的实例，也就不能够控制启动后的Service干Activity想干的事，这个Service只能干它内部定义好的功能，没有与启动它的Activity交互能力。

Over the years I had more than a few conversations with other fellow Android developers, and one constant topic that kept popping up is how much the Service component is misunderstood, across both beginners and experts. This list is the result of those discussions: it has been wandering in the back of my mind for quite some time, and I finally decided to give it physical (digital?) shape here.

This is not meant to explain in detail how Service works, the official documentation (here, here and here) does a surprisingly good job at that; instead, it’s a collection of overlooked/misunderstood/forgotten concepts that are essential to grasp in order to master the subject.

1. A Service is not a “better AsyncTask”

It’s not made to perform generic asynchronous/background operations: its purpose is to execute logic even when no Activityis visible; think of it as an invisible Activity.

Keep in mind that each Service is a special component that has a cost, not just for your app, but for the entire system.

2. A Service by default runs on the main thread, in the same process of your application

You can optionally run it in a different process, but you should avoid itunless it’s absolutely necessary and you understand all the costs associated with doing so.

See here to understand how likely it is for your process to be killed.

6. A Service can be “started”, “bound”, or both at the same time

Stopping it explicitly won’t terminate it as long as there are bound components, and unbinding all components won’t terminate it until it’s explicitly stopped (if it was ever started). Also note that no matter how many times you call startService(), a single call to stopService() orstopSelf() will stop it.

Incredibly enough, you should not bundle your business logic in the Serviceclass, but in a separate class. That way, among many other benefits, you are free to run it anywhere else, if needed. Amazing!

Now keep this list in mind, spread the word, and help stop Service abuse!

Assumptions

Motivation

There’s something that probably you can’t avoid in an Android project: Networking. Whether you are loading images, requesting data from an API server or getting a single byte from internet, you are doing networking.

Given how complex and omnipresent networking is on Android, one of the questions Android developers are facing nowadays is which solutions should I use? There are a lot of good libraries out there and you can stack one upon another in different ways.

The root of so many great networking libraries is that the offered options in the Android framework are not great and were a mess to deal with in the old days (Eclair, Froyo and Gingerbread). You had to write a lot of boilerplate code each time you were doing networking and probably you’ll be doing a sub-optimal (a.k.a. poor) job. This was the ideal scenario to solve once for all a really big and important problem and libraries started to appear and evolve.

In the old days networking in Android was a nightmare, nowadays the problem is to find out which solution best fits the project necessities.

In this article we’ll talk about a particular solution: OkHttp, Volley and Gson.

The aim of this article is just share my discoveries and experiences, learn from others and maybe help some people.

OkHttp

OkHttp is an modern, fast and efficient Http client which supports HTTP/2 and SPDY and does a lot of stuff for you. Reading how many things OkHttp does it’s a good way to understand how hard networking is: Connection pooling, gziping, caching, recovers from network problems, sync and async calls, redirects, retries … and so on.

OkHttp is a very capable networking tool out of the box, without the need of any REST library (Retrofit, Volley…) and probably is the library most developers would choose if they could only include one library in their projects.

OkHttp sits on top of Okio, a library that complements java.io and java.nio to make it much easier to access, store, and process your data. It provides fast I/O and resizable buffers.

OkHttp depends Okio, but Okio can be used by its own.

OkHttp is an modern, fast and efficient Http client which supports HTTP/2 and SPDY and sits on top of Okio.

Volley

Volley is a REST client that makes easy common networking tasks. Takes care of requesting, loading, caching, threading, synchronization and some more stuff. It’s ready to deal with JSON, images, caching, raw text and allow some customization.

Volley was design for RPC style network operations that populate the UI. Is good for short operations.

Volley by default uses as transport layer the Apache Http stack on Froyo and HttpURLConnection stack on Gingerbread and above. The reason is there are problems with those http stacks have on different Android versions.

Volley allow us to easily set up OkHttp as its transport layer.

Volley was developed by Google.

This is what Android networking looks like in Ficus Kirkpatrick (a Googler behind Volley) words. A lot of parallel async calls.

Gson

Gson is JSON serialization and deserialization library that uses reflection to populate your Java model objects from JSON objects. You can add your own serializers and deserializers as well to better control and customization.

Gradle dependencies in Android Studio

Note: The versions may be different as they are updated. Try to avoid + syntax on version numbers as is recommended.

It´s not necessary to explicitly include the Okio dependency because OkHttp already has it.

Update: As of SDK 23, apache http client was removed so it´s necessary to include in the next line in the android section of your build.gradle:

useLibrary 'org.apache.http.legacy'

All the dependencies above are official but Volley, that is not official but is trustworthy. There’s not official gradle dependency for Volley as far as I know as I’m writing this.

Volley

The way Volley works is creating requests and adding them to a queue. One queue is enough for the whole application, so each time you want to make a request you’ll get the (only) Volley queue to add the request to that queue.

I’m using a global application singleton instance of the queue with the next method:

The method we are using to create a new request queue has an HttpStack as a parameter. If you use the method that don’t provide an HttpStack Volley will create an stack depending on your API level. (based on theAndroidHttpClient for API level 9 and and HttpURLConnection stack for API level 10 and above)

As I mention before, we’d like to use OkHttp as our transport layer, that’s the reason we are using as a parameter an OkHttpStack. The OkHttpClient implementation I’m using is this one.

The next are methods to add the requests to the Volley requests queue:

/**
* Adds a request to the Volley request queue with a given tag
*
* @param request is the request to be added
* @param tag is the tag identifying the request
*/
public static void addRequest(Request<?> request, String tag)
{
request.setTag(tag);
addRequest(request);
}

We still need to parse the JSON object to our Java model. The response we are receiving on every Volley request (either String, JsonObject or JsonArray) is not really useful as it is.

You are not alone in the Android networking world.

Gson

We can customize the request to get as responses Java objects that match our data model and we are more comfortable with. All it’s needed is aGsonRequest class extending the Volley Request like in this example.

In the next example we can how would be a GET call to retrieve and parse a Json object:

The Gson parsing with a GsonRequest happens on the background worker thread instead of the main thread.

I’m providing a deserializer in the examples above but note that is not mandatory to provide serializers/deserializers and Gson can handle this very well as far as the field names in the class match (including the case) with the names in the JSON file. I like to provide my serializer/deserializer for customization.

OkHttp works as the transport layer for Volley, which on top of OkHttp is a handy way of making network requests that are parsed to Java objects by Gson just before delivering the response to the main thread

Loading images

Image loading in Android is common and complex. Threading, requesting, transformations, memory management, caches…Probably we could right an entire article about it. The good news is there are out there so many good libraries that most of us will never realize how hard it is.

ImageLoader and NetworkImageView

Volley has a custom view called NetworkImageView (subclassingImageView) that is very handy to load images. You can set an URL, a default view holder and an error image.

The important bit in the code above is the setImageUrl method, which receives two parameters: the image address and an ImageLoader (Volleyhelper that handles loading and caching images from remote URLs)

Let’s take a look at the getVolleyImageLoader method and how we can get an ImageLoader.

The only piece missing in this puzzle is LruBitmapCache. Volley does not provide us with an implementation but we can get one from here that looks appropriate and handles the cache size per device specs, which is cool.

ImageRequest

In some cases we might want not to use NetworkImageView. Image for example we want circular images and we are using CircleImageView. In that case we’ll have to use ImageRequest, which works like this:

Interesting facts

All of the components we’ve talk about in this article (Okio, OkHttp, Volley and Gson) can be used as a standalone. They don’t need each other except OkHttp needing Okio.

One of the first articles I linked in the introduction (this one) was written by Jesse Wilson. Jesse Wilson is one of the guys behind Android’s HTTP, Gson, OkHttp and Okio. I thought that deserves a mention and my acknowledgement.

OkHttp engine is backing HttpURLConnection as of Android 4.4. Twitter, Facebook and Snapchat bundles it as well.

Volley was born as a solution to be used in the Google Play Store inside Google.

Final thoughts

The Volley/Gson solution is mature and was quite popular around 2013 and 2014 mainly for been a Google solution and appear in the Android Developers website. Is still a good option to use because it just works well and it´s fast.

On the other hand, the documentation was always poor (still nowadays) and they are not being actively developed anymore (and for a while).