среда, 9 марта 2016 г.

Why static is pain

Bugs, related to static variables may be difficult to understand. I don't think it's worth investigating. As a general practice, just avoid keeping references to objects in static. When using a static reference you allways must ask youself when to free this static and when to use.

Example: keep reference to view in static variable. User closes our app, OS frees memory, so all statics are freed too. When user opens our app again, static gets newly created view. All is well.
Then, time passes and we add background running service in our app. So, when user quits our app OS can't just free memory - static may be accessed from our background service. And reference to view remains. Afterwards user open app again and static has view that was created FOR ALREADY DESTROYED VIEW HIERARCHY. And it is luck if it will work with new one. It is only one example of what can happen when using statics. Using statics is not bad. But statics need more attention from developer. They often must be freed explicitly (for example, recreated at app start). Better keep only primitive data in statics - ints, strings...

Комментариев нет:

Отправить комментарий