OOD and Passing Activity as a Parameter to Constructors of other classes
So far, to accomplish certain functional goals, I have been getting away with handing out my app's main activity object as a parameter to the constructors of other classes, which then store it as a private variable.
I do this, not because I need access to the entire activity, but rather because I need access to:
- Members (either data or methods) of the activity
- Data members which aren't initialized yet at the time those constructors were called.
It works, but I have the constant feeling that I am doing something fundamentally wrong in terms of proper OOD.
Especially in regard to point #1:
- The members that ar开发者_Go百科e so "private" to Activity become, in essence, a pool of global variables mess.
- In addition, those other classes that were created for the purpose of modularity, are now dependent on knowledge of the activity class, which makes them not really re-usable outside this app...
For these reasons, I try to avoid passing an activity as a parameter to constructors as much as possible, but in the Android development environment I find it more difficult to do, for reasons I don't fully understand yet.
My questions:
- Are there recommended "rules of thumb" that can help avoid this trap of taking "a shortcut" by passing an activity as a parameter?
- Are there cases in which passing an activity as a parameter is conceptually justified?
Generally speaking, you should avoid keeping references to the activities. If you really need, store a WeakReference to your activity. This is to avoid memory leaks.
As you said, by passing a reference to an activity, you introduce a dependency between the other object and your activity class. Give some sample code so that we could give an example of how to refactor it.
I have found it best to keep values that multiple classes will require in a separate Util class. That way, you do not have to pass the main Activity around to other classes.
An alternative to this is to pass the required values that the main Activity has as parameters to the other classes as needed.
To your 2nd question, I cannot think of any reason that you would have to pass your main activity and then call methods on it.
精彩评论