03 May 2016

Android n00b lessons

I've been training a couple of relatively junior Android developers recently and I've seen a few mistakes repeated. I thoughts I'd mention them here in the hope it will help someone else. This isn't supposed to be a laugh at anyone's expense, just a discussion about how to improve your code and become a better developer.
  1. Don't close a cursor properly
    I see this in on-line examples, in old code and in new code written by juniors. The fact is there are a lot of things that can go wrong when using a cursor, so you need to be a bit careful and make sure you don't throw an error or waste memory. 
    1. First and foremost close the cursor.
    2. Your cursor might be null
    3. Use finally to close your cursor, it works really well!

    Cursor data = context.getContentResolver().query(MyProvider.DETAILS, null, null, null, null);
    
    try {
        if (data != null && data.moveToFirst()) {
            retVal = data.getString(data.getColumnIndex(columnName));
        }
    } finally {
        if(data != null) {
            data.close();
        }
    }

  2. Catching an error badly
    Arrrg! I see this far too often. An empty catch block. Even if it's just a Log.e, that's better than nothing. OK I'll admit there are some situations where you just don't care if an error is thrown (like above), but all too often people just throw the try in to avoid compile errors and leave the catch empty. Don't do it!

            try {
                int a = 1;
            }catch(Exception e){
                    
            }
    

  3. Excessive use of RecyclerView
    RecyclerView is new, it's cool and it's heavily publicized. That doesn't mean you should use it ALL the time. If you've got a small simple app with one ListView that will show about three elements, please don't bring an entire new library into the project. A ListView is OK. If your ListView is small and your needs simple, don't panic, you can use a ListView. The world will not end, I promise. Yes the RecyclerView is efficient, especially when you want to use animations or change elements but sometimes it's like cutting the grass with a machine gun. I don't want to say RecyclerView is bad, it's a fantastic tool, but use your perspective and let's keep it simple people!

  4. Variables in a loop
    This one was really interesting. Conventional wisdom often states you should never create a variable in a loop, and to be honest I always held with this. However I did some research recently and it seems that it's actually most efficient to declare the variable in the smallest scope possible. If that means declaring it in the loop, then fine, as long as that's NOT then used outside the loop.

    for (Person person : people) {
        String desc = person.getDescription();
        ...
    }
    

If you've any more suggestions then I'd love to hear them.

No comments: