I need to access a method through the context, but I have no way to access it since the module in which this method is located does not have visibility with the app module and I cannot give it to it either, since it would cause a circular dependency error:
private static synchronized String createDataPath(String path) {
File fileDir = context.getExternalFilesDir(path);
if (fileDir != null) {
return fileDir.getAbsolutePath();
} else {
return null;
}
}
Before, that context was taken by storing the context in a static variable, but this causes me a memory leak and I have already seen that it is not recommended at all to do it this way.
When I have had context problems, I accessed the instance of the Application class that provided me with a context, but in this case I cannot access the Application class because it is not in the same module.
The other option is to pass the context by parameter of the method but it is a project with hundreds of classes and methods, so passing the context by parameter would make it have to pass the context to all the methods that depend on it, thus creating a pyramid gigantic, and it is what I try to avoid, what other option do I have?
One option is to move your class
Application
to a separate module and add it as a dependency to the other modules. So you could use it in the same way as in your main module. But this would be propagating bad practice.If you followed good practice, it shouldn't matter much to you which module a class is in. The way to treat it is the same as that of a class in the same module.
In a method as simple as the one you show, the ideal is to pass it as a parameter. But you don't need the entire method chain to have it as a parameter, only the class that calls it directly needs it.
For example if you have class A that calls a method of class B and class B calls the static method, only class B needs to have a context.
If you use a dependency injector like Hilt , you simply add the @ApplicationContext (or
@ActivityContext
, depending on your needs) annotation to the parameter and the context will be passed automatically even if there is no reference to aContext
in that class.If instead the method is more complex or is also called by a static method, you should follow good practice and make it a regular method. So according to the dependency injection pattern, methods should not have the parameter
Context
but the constructor of their owner class.Then you inject it into the constructor of the classes that require it.
In classes that extend android components, the way to inject dependencies is like this
And so you can keep replicating this pattern in all the places you need it. Unless you're abusing static methods, you shouldn't have a problem.
In this way you get independent classes, easy to test and you would never have to explicitly pass a
Context
parameter even if all the classes had it in their constructor.