Android is designed in such a way that in order for a method to read a resource, it must have a access to a Context.
Since most of the classes in my application rely on the flexibility of string resources (e.g. changing language without having to change code, etc.), my simple solution was to pass a Context in their constructor, to provide resource access to each such class.
It doesn't make sense for me to only pass a string in the constructor, because the class needs the flexibility of access to a varying number of strings.
So, to simplify things, I only pass Context, and whenever a string resource is needed, I just use Context.getString().
Is this a sign of bad design?
Is there a better way to accomplish this?
This is the Service locator pattern - you pass around a service locator (often called "Context") and get the required dependencies from it. It is not an anti-pattern, and is not that much of a bad design, but usually dependency injection is considered superior.
What you are doing is - passing the service locator even further down the object graph. What is advisable is to give each class only the dependencies it needs. So instead of passing Context
in the constructor, you pass all the strings it requires. That way you won't be violating the Law of Demeter
This is one of the rare occasions where a globally accessible singleton class may be better than passing the Context
to every single class.
I would consider creating a singleton for localization, then use the Context
inside of there (unless you need other aspects of the Context
all over the place).
Of course, this is a matter of taste and preference. YMMV
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With