technology

I’m making a note here, @HugeSuccess

Despite having used android studio for quite some time now, I’m sheepish to admit that I have only just realized the extent of the annotation options available for both IntelliJ and specifically Android. Since finding out about a couple of these, they’ve saved me from quite a few cases where I might otherwise have introduced an NPE or other error into my code. Here I’ll just run over a couple of the ones I use most frequently, but there are plenty more provided by android or by IntelliJ (If you use Android Studio)

@Nullable / @NonNull

Nice and simple, these do just what they say on the tin. Annotating a method as nullable will cause Android Studio to check all the uses for potential NPEs, and has definitely saved me a headache a fair number of times. However, there are some methods where you might get a null output, but only with a certain input – here’s where the more complex @Contract annotation comes into play. For example, what if you have a method that is guaranteed to return null, but only if the input is null? Well, for that there’s

@Contract("null -> null")

Or perhaps it might throw an exception?

@Contract("null -> fail")

You can read up on the @Contract grammar here

Threading

What about methods that you know need to be run on background threads? Or foreground threads? Nobody likes NetworkOnMainThreadException, especially when your IDE can be told where they might occur. If you have a method that you know performs network activity (or anything else you feel should be kept far from the main thread, like some hefty DB operations) you can use @WorkerThread to hint that it should never be called from a UI thread context. On the other hand, if you have code that rearranges your views, you’ll want to make sure that it’s @UiThread.

Testing

If you have a testing flow that involves replacing instances of things with mock instances, it can be good to specify that the setter for your Clock instance is only really meant to be messed with by tests, and not by application code that wants to do something a little funky. @TestOnly and @VisibleForTest both help document this by alerting you that the method is only visible for test purposes, and should only be called from a testing context.

Know of any other useful docmentation or linting aids for Android development? Let us know in the comments!

Discussion

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s