Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

android singleton vs static methods

I need to load some files and store them in a static variable.

The load and getter methods are required in almost every Activity.

I was going to make the methods static, but some blogger dis-liked it.

Main advantages and disadvantages for both approaches for me are as follows.

singleton

advantages : Ability to keep polymorphism.

disadvantages : Have to call getInstantace methods in every Activity.

static method is vice-versa.

Please guide me in choosing between the two or any other approach.

Any help would be appreciated.

like image 732
tompal18 Avatar asked Jun 20 '26 11:06

tompal18


2 Answers

I would avoid using Static variables in Android, because Android often clears all Static data from your class if your app is paused and the phone is short on resources, leading to unexpected Null Pointer Exceptions. Search Google for "Android Static Null" for a better explanation.

Either ways (Static methods or Singletons), you should make sure your app has the ability to save state and restore it in case Android clears your static variables.

like image 171
Abhinav Manchanda Avatar answered Jun 22 '26 01:06

Abhinav Manchanda


You can find "some blogger" who pretty much dislikes anything. There's nothing wrong with static methods, so long as any state they operate on is local to the method/passed in with each call (same caveat applies for instance methods on a singleton).

Either approach should be fine, just pick the one you prefer. As a general rule of thumb, go with static methods if your singleton instance would not be holding any state that is potentially mutable at runtime. Otherwise, if the singleton is meant to hold state and not just serve as a repository for a handful of utility methods, then make it a singleton.

The only halfway reasonable argument against using static methods that I have come across is that static methods are problematic to mock-out for unit-testing purposes. But my guess is that you are probably not doing mock unit-testing, and I think the value of testing with mock objects is generally overstated when you look at the value that comes out of it relative to the amount of work that goes into setting up the test case(s).

like image 27
aroth Avatar answered Jun 21 '26 23:06

aroth



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!