0

Is there ever a case in Android within singletons where I would want a variable to be public as opposed to it being private and accessed from outside the class with a getter/setter? Is there ever a case where I would want a variable to be static as opposed to being nonstatic and accessed through the instance of the singleton? I'm trying to modify my code to make garbage collection as easy as possible.

public static int someInt = 0;
Jon
  • 7,941
  • 9
  • 53
  • 105
  • 1
    Allways thinks about encapsulation and avoiding mutable global states (worry about that first, dont worry about garbage collection..) – Anis LOUNIS aka AnixPasBesoin Aug 25 '15 at 16:33
  • 1
    These design decisions are context sensitive. Personally, I believe you should never expose fields. Supplying a getter for a private field will allow you to easily decompose in the future. These decisions have nothing to do with GC, and your example of `someInt` isn't relevant, as primitive values are not picked up by the GC (unless its a field value within an object). You should pay more attention to when you create objects and who references them and for how long – Vince Aug 25 '15 at 16:38
  • 1
    Never go full public static Context mContext (attempt to be funny after watching Tropic Thunder). Everything else sort of depends on the situation. Some devs even say that singletons are evil (which is up for debate). – Spidey Aug 25 '15 at 16:40
  • Thanks. What I'm getting at here is whether using public/static variables is ever a good idea or whether it can be uniformly described as something to avoid and code in a different way. Because if it is a design decision that has merit some of the time, then I'm worried that by coding it out I might end up breaking something – Jon Aug 25 '15 at 16:41
  • 1
    public vs private is described here http://stackoverflow.com/questions/1568091/why-use-getters-and-setters – Spidey Aug 25 '15 at 17:02

1 Answers1

1

Generally, class with a public field is a code smell in my opinion. If you need to add synchronization because the field is used by multiple threads, you are screwed! Better to encapsulate the field with accessors (getter/setter).

A static field is useless within a singleton: There is only one instance of the singleton by definition, so there is only one "instance" of the field. The only exception would be for constants (static final)

nicopico
  • 3,606
  • 1
  • 28
  • 30