Anroid MVP tips

by Goran Siric on Sunday, September 10, 2017 7:15 PM

Naming methods in presenter

Suppose you  want to exit you application when user press back button.

In your View (activity) you can have this code

 

@Override
public void onBackPressed()
{
    presenter.exitApplication();
}

 

On first sight, it seems everything is fine with this code. 

Now look at your presenter exitApplication() code: 

public void exitApplication()
{
    MyApplication.getInstance().exitApplication();
}

 

Now, looking at this code, you can ask yourself why and when View decided to call this method? Looks that Presenter is here only to forward some method calls.

Now you must to inspect View code!

As you can see, responsibility for "what to do onBack", is actually in View vode, just because the method in presenter is called exitApplication().

Methods on presenters should map to user actions or events, so presenter can choose what to do depending on user action. 

In our example, better way is to have presenter.onBackPressed method, and let presenter choose what to do when user press back button.

This way you will not need to inspect View (activity) code wondering why some presenter code is called.

So better code would be:

View code:

@Override
public void onBackPressed()
{
    presenter.onBackPressed();
}

Presenter code:

public void onBackPressed()
{
    MyApplication.getInstance().exitApplication();
}

Author
Goran Siric

Blog about programming



  Hi folks! I am proud to present: 
Bubble Zoo Escape, my first Android game built using AndEngine 
If you have a time, please download and give feedback!

If you found this useful,
you can buy me a coffe :)

By me a coffe through PayPal :)


Featured articles

AndEngine - Textures tips and tricks

What you should know abot textures before get started programming your first game.

GIMP script for creating Android icons at once

Script for creating Android icons for different screen resolutions at once. Icons can be saved using standard Android icons naming conventions and saved in appropriate folders.

Creating Android button with image and text using relative layout

Source code with examples how to use relative layout to create nice buttons with text and images in Android

Android application and the Internet

Tutorial about connecting to the web pages on the Internet from Android application, using both POST and GET web requests.

Copyright 2011 by Goran Siric