Home > Articles > Mobile Application Development & Programming

Simple Tips for Better Android Development

  • Print
  • + Share This
Ian G. Clifton, author of Essentials of Android Application Development LiveLessons, discusses some simple ways to improve the quality of your Android code immediately.
From the author of

When you first begin developing or switch to a new platform, you’ll deal with a lot of unknowns. You can very easily make mistakes (despite good intentions) just because you aren’t aware of standard techniques and best practices. This article highlights a few things to consider when developing with Java, and for Android in particular.

Don’t Accept Null Unless Being Explicit

It doesn’t take long for a new Java developer to encounter his or her first NullPointerException. It is one of the most common causes of app crashes, despite the fact that it seems really easy to avoid. After all, just don’t use null when you need to have an object, right? Unfortunately, as a code base grows, it becomes more and more difficult to understand all the possible paths, so it can be unclear whether a reference is null or not. The situation becomes even more complex as multiple developers work on a project or third-party libraries are added.

You can’t always avoid having a null pointer handed around in code, but you can develop better coding practices to minimize the problem. In general, your methods shouldn’t take null as a parameter unless intentionally allowed. Consider this example:

public List<User> getUsers(int limit, Filter filter) {
    // ...

What happens when you pass in null for the Filter? You don’t know unless you dig into that code, which might pass off the null elsewhere, and that other place may or may not require it. You quickly get into a position where you actually don’t know what to expect; since you’re on a deadline, you make an assumption that it is (or isn’t) okay, and possibly you create a bug to bite you later. Now consider this same method with some changes:

 * Returns a List of Users up to the specified limit
 * @param limit int maximum number of users to return
 * @param optionalFilter Filter to further restrict results or null to just use the limit
 * @return List of Users requested, empty List if no results
public List<User> getUsers(int limit, Filter optionalFilter){
  // ...

First, the comments explicitly say that null is okay. Even without the comments, the name of the parameter, optionalFilter, strongly implies that it can be null. As a bonus, you know that this method is intended never to return null, which means you can directly iterate over the result.

Use Annotations

One powerful feature of Java that is generally underutilized by new developers is annotations, which are basically metadata about code. Annotations can do virtually anything, such as preventing you from accidentally overriding methods, or even generating code for you. The power of annotations can be intimidating, so many developers avoid them altogether. If that’s you, force yourself to change; it won’t take long before you see the benefits.

A great way to start is with the easy-to-use @NonNull and @Nullable annotations from the Android support repository. If you’re using the support-v4 library or appcompat-v7, you’re ready to include the annotations. If not, make sure you have the Android Support Repository from the Android SDK Manager and then include the following in your Gradle dependencies:

compile 'com.android.support:support-annotations:21.0.3'

The @NonNull annotation means that the given parameter or return value cannot be null (or the app will crash), so Android Studio can warn you if you attempt to pass a null value where you shouldn’t. The @Nullable annotation means that the given parameter or return value can be null, letting Android Studio warn you if you try to use a value that might be null without checking (such as our previous optional filter). Our method could be updated to look like this:

public List<Object> getUsers(int limit, @Nullable Object optionalFilter) {
  // ...

This approach ensures that you cannot accidentally return null in this method and you don’t accidentally use the optionalFilter without checking for null first.

Some of the power of annotations comes when you start adding them all around your code and you can make quick guarantees about behavior. This technique will keep you from writing unnecessary null checks and help ensure that your code matches its contract.

One important note: You need to tell Android Studio to enforce these rules. Follow these steps:

  1. Open Settings and select Inspections on the left side (or type it in the search box at upper left).
  2. Go to Constant Conditions & Exceptions under Probable Bugs on the right (or search for it in the upper middle search box). Make sure that this option is checked.
  3. Click the Configure Annotations button. Make sure android.support.annotation.Nullable is in the top box and android.support.annotation.NonNull is in the bottom box (you can add them with the plus button). Click each of them, click the check button so that your generated code will include the annotations, and then click OK.
  4. I also recommend that you increase the Severity to Error to prevent you from building an app that ignores these annotations.

Don’t No-Op

A “no-op” (short for “no operation”) is a portion of code, such as a method, which does nothing in certain situations. One of the easiest ways to add difficult-to-troubleshoot bugs to your code is to see a NullPointerException in your logs, jump into that method, check whether the reference is null, and just return if it is. For instance, if the previous getUsers method required a Filter object, a poor solution would be to return null or an empty List if the Filter was null. The problem is that it’s easy to pass in null accidentally and then pass along the bad result to another method. Two weeks down the road you get crashes in your ListAdapter because it’s trying to get the size of a null List of Users. Now you have to backtrack through every method call that could lead to the display code, looking to find out how it could be empty, which could take hours. A no-op becomes a particular pain when it ends up affecting UI code, because that code is often triggered via the Looper (the class that handles Android’s message loop), so your stack trace won’t even include the methods that passed around the bad results.

Be Defensive

How do you handle the case of a method receiving null when it shouldn’t? Throw a NullPointerException! The idea of purposely throwing an exception often makes newer developers uneasy, because an exception can result in a crash. Crashes are bad for users, but they’re good for developers; they let you find out where something went wrong and fix it immediately. Instead of having the code in an inconsistent or unexpected state, a crash stops it from going forward. The earlier in the process that you throw an exception, the smaller the amount of code you’ll have to look through to find the problem. This is especially important if you’re writing any kind of interface code or a library to be used by other people. In that case, you really want to throw an exception the instant a method is called with any invalid parameters. Consider this updated version of the getUsers method:

public List<User> getUsers(int limit, Filter requiredFilter) {
   if (limit < 1) {
       throw new IllegalArgumentException("limit must be 1 or greater; received " + limit);
   if (requiredFilter == null) {
       throw new NullPointerException("requiredFilter cannot be null");
   // ...

Now it’s impossible for bad values to be passed to some other method. Any bad value results in a crash that calls out what was wrong. One of the most important things you can do with a throw like this is to give the actual value that was passed in, such as with the limit in this example. Without it, the developer only knows that some int less than one was passed in. With the actual value, the developer can see something like -2147483648 being returned, immediately knowing that Integer.MIN_VALUE was used by accident somewhere. It is pretty common to see the actual value and immediately realize what went wrong (for example, autocompleting the wrong constant).

Learn the Libraries

Android has been around long enough now that a lot of great libraries have been created, so you don’t need to reinvent the wheel. Any time you come across a challenge that you know must have been solved somewhere, take some time to look online for a library that handles that problem. You’ll save yourself a lot of work (and probably quite a few bugs); plus, you will probably learn more about development techniques and the Android community in the process.

If you’re not sure where to start, look at the Square libraries on GitHub. For example, the early days of Android necessitated that every app have its own HTTP layer, which would easily be thousands of lines of complex code to handle threading, callbacks, errors, and so on. Now, you can just use Square’s OkHttp library to make web requests with just a few lines of code. That library also is likely more efficient and better tested than what you’d write from scratch. If the web requests are just for using REST services, take a look at Retrofit.

In a lot of cases, multiple libraries are available that can be used for a given problem. For example, downloading images can be handled by another Square library called Picasso, Google’s Volley, or any one of many other libraries. Which one you use is up to you. Generally, you should look at the library’s API, documentation, when it was last updated, and a small sample of the code (you can usually spot red flags in bad libraries quite quickly). Another good idea is to do a quick search about that library to see what other developers are saying about it. When you take advantage of existing libraries, you can focus more on writing the code that is unique to your app, making it better and more reliable.

Wrapping Up

Most of the tips I’ve discussed in this article are about making your code predictable. Whether another developer is integrating your code today, or you’re providing an update to your own code six months from now, you’ll avoid a lot of common bugs by having made it obvious exactly how your code works and what values are allowed. Adding good comments, using clear argument names, including annotations, and throwing exceptions instead of silently accepting bad values will save you far more effort in the long run than the little bit of extra work those tasks take up front. On top of all that, taking advantage of quality libraries means that you don’t create new bugs by writing code for features that are readily available and already well tested.

  • + Share This
  • 🔖 Save To Your Account