Anroid MVP tips

by Goran Siric on Sunday, September 10, 2017 5: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

public void onBackPressed()

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

Now look at your presenter exitApplication() code:

public void 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:

public void onBackPressed()

Presenter code:

public void onBackPressed()

Goran Siric

Blog about programming

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

By me a coffe through PayPal :)

Featured articles

Integrating ChatGPT shared links with Sourcetree

We'll guide you through the process of incorporating ChatGPT shared links into your commit messages.

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.