· 2 min read Posted by Touchlab
Static Application Reference
I’m a bit of a stickler for passing Context around methods rather than keeping a handle on the context in object fields and whatnot. There are some obvious reasons, like being careful about memory leaks and whatnot. I feel like its mostly because I like to be intentional about such things in code design.
However, as time goes on, I start to question some ideas.
We did a code “rescue” for a client last year, and the previous consultants had done some some extremely ugly things with the code. The worst was keeping a Context reference in a static, and calling on it from deep (and I mean DEEP) in some methods. They did some other terrible things, like calling the same methods from unknown threads and doing I/O (as it turned out, sometimes they were in a background thread, sometimes in the main, but I’d put money on the programmer not understanding why that was a problem).
The worst thing about the code was that the Context instance was being set in the launch Activity (which was a splash screen, btw 😛 ). The obvious problem here, dear reader, is that you don’t always go through the launch Activity when the app starts. You may reload from the Activity that was last visible, when Android shut your app down. Of secondary concern was that the Context instance was the Activity itself, which is just bad news (memory).
Anyway, I have this reflexive aversion to keeping Context objects anywhere in fields, much less in statics. But, sometimes in life you need to question your views (and not start a sentence with ‘but’. But, whatever).
What about keeping the Application instance in a static in a custom Application class? Set it during onCreate. From a technical perspective, I have a hard time coming up with a reason why you shouldn’t do that. There won’t be memory leaks associated with doing that. Unless there’s a tear in time and space (or a bug in Android), that method will always be called, regardless of what Activity you’re being dumped into.
From a design perspective, it feels lazy. Thoughts? Leave in comments!
Full disclosure, while I was actually thinking about this topic, I posted it because I wanted to try out the newly added comments section.