Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVP: how to write to log from Presenter

Tags:

android

mvp

mosby

I use Mosby to build apps with MVP-pattern. And this is one of the rules:

Don't use android library code in Presenter.

But what if I want to log something from Presenter? The only way that I see is to use System.out.println(); but it sounds not good. Any idea?

like image 265
Alexandr Avatar asked Feb 07 '23 04:02

Alexandr


1 Answers

The reason not to use Android Library code in the Presenter is so that when you come to write unit tests there are no dependencies on the Android code in your class and as such it can run directly on the JVM.

If you find yourself needing to use Android code then the way I do this is to hide it behind an interface. That way you can use one implementation in your production code and another one in your tests.

So create an interface called Logger:

public interface Logger {

    void logd(String tag, String message);
}

Then for your production code you can use:

public class LoggerImpl implements Logger {

    public void logd(String tag, String message) {

        Log.d(tag, message);
    }
}

But when you are running tests you can use another implementation:

public class LoggerTestImpl implements Logger {

    public void logd(String tag, String message) {

        System.out.println(tag + " " + message);
    }
}

Add a Logger dependency to the constructor of your Presenter. At runtime give it a LoggerImpl, during tests give it a LoggerTestImpl.

As an aside you could consider whether you actually need to be doing much logging from your Presenter in the first place. Android Studio allows you to have breakpoints which don't suspend the code and will log a message to the debug console when they get hit. This will depend on your requirements of course though.

like image 101
Jahnold Avatar answered Feb 20 '23 01:02

Jahnold