I have just started using MVP in android development. As per different tutorials found on web, I am creating 5(viewInterface, presenterInterface, presenterImpl, interector, and interectorImpl) files for each fragment. Is there any way by which i can reduce the number of these files.
Thanks
As you have come to know basics of Clean Architechure. The following example depicts how actual your MVP pattern is implemented.
Example:
interface BaseContract {
interface BaseView {
//Methods for View
void onDoSomething();
}
interface BasePresenter {
void doSomething();
}
}
class BaseMainPresenter implements BaseContract.BasePresenter {
BaseContract.BaseView view;
BaseMainPresenter(BaseContract.BaseView view) {
this.view = view;
}
#Override
public void doSomething() {
if (view != null)
view.onDoSomething();
}
}
class DemoClass implements BaseContract.BaseView {
//Create object of Presenter
/****
* Example :
* BaseMainPresenter baseMainPresenter = new BaseMainPresenter(this);
*/
#Override
public void onDoSomething() {
//Deal with Context here.
}
}
You can refer as MVP Pattern with this following link :-
Link : https://github.com/Archish27/Retrozing
Yeah- don't do whatever it is you're doing. MVP is a good pattern for some usecases, but there's never a reason for more than 3 classes- a model, a view, and a presenter. Any tutorial that is going into that depth is being way over formal and is actually a harmful tutorial.
Android is basically MVP by default. Your Presenter is your Activity class. Your View is your layout- that hierarchy of View classes. Your model is whatever data you need to run your app.
Don't get hung up on overly formal explanations of patterns, and don't apply patterns to apply a pattern. The real use of patterns isn't a goal to make your application look like that, the real use of a pattern is a way to describe what you're doing to other architects/programmers. You should never look at a pattern and try to find ways to use it or look at a problem and think "what patterns can I use". You should see a problem, think of a solution, and that may be a pattern. By the time you're ready to study patterns, you should have seen the vast majority of them in code already.
Related
I am using the visitor pattern to abstract payment processing away from the UI code in android. I have some doubts on what i should pass into the visitor constructor inorder for the view to get a call back once its done processing the payment.
Let me show you what i have so far:
i am dealing with 2 payment systems, thus two payment strategies (brainTree and Stripe):
public class BrainTreePaymentStrategy implements IVisitable {
#Override
public void makePayment() {
}
#Override
public void accept(Visitor v) {
}
}
public class StripePaymentStrategy implements IVisitable {
#Override
public void makePayment() {
}
#Override
public void accept(IVisitor v) {
}
}
public interface IVisitable {
void makePayment();
void accept(IVisitor v);
}
public interface IVisitor {
//list out all the classes the visitor can visit now
void visit(StripePaymentStrategy stripePaymentStrategy);
void visit(BrainTreePaymentStrategy brainTreePaymentStrategy);
}
//now critical, lets create a real concrete visitor that can actually do the work:
public class PaymentStrategyVistor implements IVisitor {
#Override
public void visit(StripePaymentStrategy stripePaymentStrategy) {
//process the braintree payment here, but how to give call back to UI ?
}
#Override
public void visit(BrainTreePaymentStrategy brainTreePaymentStrategy) {
//process the braintree payment here, but how to give call back to UI ?
}
}
i am using uncle bob's clean architecuture so my network calls are through usecases and also im using mvp for my presentation layer so i have access to presenter and usecase if needed.
So again my question is regarding PaymentStrategyVistor class, what do you think if i passed in the presenter as a constructor parameter. i for example , could then call presenter.doBrainTreePayment("someToken"); i could do that in the visitors visit(BrainTreePaymentStrategy brainTreePaymentStrategy) method. is this how you all would do it ?
Your suggestion (passing the presenter to the constructor of each visitor) seems to be totally fine.
Looking from clean architecture perspective this all is fine as long as u do not violate the dependency rule. so if ur strategy and visitors live in the "interface adapter layer" u can easily pass the presenter. on the other hand if ur strategy/visitor belong to the "use cases layer" than passing the presenter would violate the dependency rule and u should not do it.
For a more detailed discussion on presenters in clean architecture see my blog post: https://plainionist.github.io/Implementing-Clean-Architecture-Controller-Presenter/
Planning on implementing MVP architecture for a MVC type android app. I have a concern on how I can make a presenter that will have multiple
models.
Typically a presenter's constructor will look like this:
MyPresenter(IView view, IInteractor model);
This way I can swap out dependencies when I'm testing and mock out view and model easily. But imagine my presenter is tied to an activity that must be multiple network calls. So for example I have one activity that does an API call for login and then another one for security questions, and then a third one for GetFriendsList. All those calls are in the same activity theme. How to do this with the constructor I showed above? or what is the best way to do this kind of thing? Or am I limited to having just one model and calling the services within that one model?
Presenter constructor need only the view.You don't need to dependent on the model. define your presenter and a view like that.
public interface Presenter{
void getFriendList(Model1 model);
void getFeature(Model2 model2);
public interface View{
void showFriendList(Model1 model);
void showFeature(Model2 model2)
}
}
now your implementation class has dependent on view part only.
rest your method will handle your model
class PresenterImpl implements Presenter{
View view;
PresenterImpl(View view){
this.view = view;
}
void getFriendList(Model1 model){
//Do your model work here
//update View
view.showFriendList(model);
}
void getFeature(Model2 model2) {
//Do your model work here
//updateView
view.showFeature(model2)
}
}
Would it be an anti-pattern if from a Presenter layer I open an Activity?
If so, should I manage the navigation of the app from the View Layer?
Yes it's an anti-mvp-pattern. Based on passive view in MVP, you lost your testability, because you don't have to deal with the android framework in your presenter.
So it's better to manage the navigation of the app from the View Layer.
class MyPresenter {
MyPresenter.View view;
void backButtonClicked() {
view.navigateToHomeScreen();
}
public interface View {
void navigateToHomeScreen();
}
}
class MyActivity extends Activity implements MyPresenter.View {
#Override
void navigateToHomeScreen() {
startActivity(...)
}
#OnClick(R.id.my_button)
void onClick() {
presenter.backButtonClicked();
}
}
Also another advantage of this way is that it will be easy to replace activity with a fragment or a view.
Edit 1:
Morgwai said this way will break separation of concern and single responsibility, but you cannot have single responsibility every where. Sometime you need to violate it. Here is an example from Google for MVP:
TaskDetailPresenter calls ShowEditTask which is responsible to open a new Activity inside TaskDetailFragment.
But also you can use CommandPattern which is a better approach
interface NavigationCommand {
void navigate();
}
So, Presenter will use it when it needs.
As I wrote in my comment to the accepted answer, I think that managing navigation from the view layer is a clear breaking of separation of concerns rule: views should contain ONLY methods to update current UI screen.
The problem originates from the android platform design as Activity and Fragment classes contain both methods to operate on UI screen and to send intent objects that start other activities like startActivity.
A clean way to solve this would be to create some Navigator interface that would contain methods related to navigation, make activities implement it and inject it into presenters as well. This way at least from the presenters' standpoint navigation and UI manipulation would be separated. It may however look odd from activities' standpoint: now they would often implement both interfaces (Navigator and View) and pass their reference 2 times to the presenter. If because of this reason you decide to manage navigation from your view layer then at least keep methods for navigating separate from those for manipulating UI: never perform navigation and UI manipulation in the same method.
In my opinion it would be better if you open an activity from the View Layer. I prefer that Presenter knows about Activity as little as possible.
If there is some condition of what activity should be started, you can use something like this:
public class Presenter {
private ViewsPresentation mViewsPresentation;
public void someButtonClicked() {
if (/*some condition*/) {
mViewsPresentation.startFirstActivity();
} else {
mViewsPresentation.startSecondActivity();
}
}
public interface ViewsPresentation {
void startFirstActivity();
void startSecondActivity();
}
}
I have made this solution (in Kotlin):
I created an Interface called ViewNavigator
interface ViewNavigator {
fun navigateTo(target: Class<*>)
}
Then I made the View Interface Implement it
interface View : ViewNavigator {
//...
}
Then the Actual View (the activity) can override the navigateTo function
override fun navigateTo(target: Class<*>) {
startActivity(Intent(this, target))
}
So, whenever I want to navigate to any activity, I can simply write that in the presenter class. For example:
override fun onAnimationFinished() {
view.navigateTo(HomeActivity::class.java)
}
I started to study MVP as I read about it is a very good pattern for developing Android apps.
I have a class (Model) for example:
public class Level {
int difficulty;
int enemies;
public int getXpReward() {
return enemies * difficulty;
}
}
And I have another class (View) for example:
public class LevelView extends FrameLayout {
TextView xpRewardTextView;
/*ctr and view init......codehere*/
public updateOptionOne(Level level) {
xpRewardTextView.setText(Integer.toString(level.getXpReward()));
}
public updateOptionTwo(int xpReward) {
xpRewardTextView.setText(Integer.toString(xpReward));
}
}
Should I call the optionOne function from my Presenter so passing a whole instance of Level?
Like:
myPresenter.updateView(MyDb.getLevel())
Or
Should I call the optionTwo function from my Presenter so only passing the very data we need to the View, like only JAVA type attributes
Like:
myPresenter.updateView(MyDb.getLevel().getXpReward())
So basically my question is do Views can have Model types as arguments of their update functions? Because I read an MVP principle about the Views should not know anything about Models.
In this case yes keep the View simple as possible.
For larger and more complex application you sometime need classes to communicate between the view and the presenter. In that case you should have a Model for the View layer and one for the data layer and convert them at the presentation layer.
I have been coding an Android app that has a lot of code dedicated to it. As you can imagine, there's lots of case-driven code in there. Because most of Android callback functionality is based on integers and ItemIDs and requestCodes, there is a lot of functionality built into switch statements or if-then-else constructs.
What are the best practices for organizing/refactoring this code in a better way? What have you found that works to reduce the amount of code and clarifies it at the same time? Is a huge amount of small classes going to hurt Android performance?
Thanks in advance.
A large number of classes is not going to affect the performance of the application. Some good practices in Android, however, include placing values like integers, item IDs, and request codes into a Resources xml file.
You will also see a lot of Callback classes as inner interfaces of the Object they relate to:
public class MyObject
{
private Callback callback;
private Object returnObject;
public void setCallback(Callback callback)
{
this.callback = callback;
}
public void doSomething()
{
//do something - could be an anync task or other that assigns returnObject
callback.invoke(returnObject);
}
public interface Callback
{
public void invoke(Object obj);
}
}
Then you can use this as follows:
MyObject obj = new MyObject();
obj.setCallback(new MyObject.Callback() {
#Override
public void invoke(Object obj) {
Log.i("Callback", obj.toString());
}
});
obj.doSomething();