Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is having to pass Context to most classes a sign of bad design?

Tags:

java

oop

android

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?

like image 964
uTubeFan Avatar asked Sep 20 '11 19:09

uTubeFan


2 Answers

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

like image 163
Bozho Avatar answered Nov 15 '22 01:11

Bozho


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

like image 41
Eric Farr Avatar answered Nov 15 '22 01:11

Eric Farr