Tuesday, 2 August 2011

Objects and lifecycles

Android uses a Java-like programming language. I like objects, though I would prefer a more powerful implementation of property getters and setters in Java.  I was a bit surprised that in the examples of Android code I've seen there hasn't been more use of objects. Now I know why. Objects are expensive on some Android implementations because the object has to be created and therefore cleaned up. On devices with very small amounts of memory, or with a lot of apps running garbage collections are needed and these can cause a pause on the user interface. On Android 3.0+ there is a concurrent garbage collector but it still takes work.

This seems like a shame to me, objects are handy and I'm sure that sometimes I will use them, but I need to moderate my natural inclination to create an object for any and every purpose. I'm sure some Android devices would handle object management without any problem, but I need to consider some smaller devices too.

Each activity (screen) has an object associated with it so creating fields in there to use seems to be the main route to storing and manipulating data. Direct access to the field is recommended, not using getters and setters to save resources, so the fields are reduced to simple variables with limited scope. Indeed it is further recommended to be careful about how intermediate variables are used, so that a method that returns an object does not create a temporary object that just needs to be cleaned up.

If the use of objects is such a problem I wonder why Java was the chosen language for Android. I think I'll have to experiment some more - so far using objects works for me both on the emulator and my Android devices, I just need to not get carried away.

I have also been looking at the life cycle of Android apps. It did feel a bit odd at first because it seemed that the programmer was not in control of the life cycle of an app. In reality it works well and is just a variant of any other event-driven UI. It is a bit odd to not have a way to end an app, but if the user closes every activity etc Dalvik cleans up. The life cycle is well documented, but it is important to do the right things in the right place - that is what bit me about changed fields not getting displayed.