2
\$\begingroup\$

While implementing Android Activity component using MVP pattern a discussion arose - who should be responsible of creating list adapter - view or presenter? If presenter creates adapter, apparently View needs to provide Context for Presenter to be able to instantiate adapter:

public interface MyView {

void setAdapter(ListAdapter adapter);

Context getContext();
}

And then presenter could easily set adapter:

view.setAdapter(new MyAdapter(view.getContext(), ...));

The second approach would be allowing View to create Adapter object and thus expose data to it, for example:

public interface MyView {

void setAdapter(MyData[] data);

}

In first example I am exposing Context object that I would like to avoid, but in the second example I am letting View to decide on adapter implementation and expose data to it as well. What do you suggest?

\$\endgroup\$
3
\$\begingroup\$

I would keep the presenter free from Android code, so you can unit test it. You can pass the data from your presenter to the view and instantiate the adapter there.

public class MyActivity extends Activity implements MyView {

     public void setMyAdapter(List<String> items) {
         ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
            android.R.layout.simple_spinner_item, items);
}

and call this method from the presenter via the MyView interface.

\$\endgroup\$
  • \$\begingroup\$ So the second approach. What limits me from unit-testing it in the first approach? \$\endgroup\$ – RooMan Aug 3 '16 at 8:54
  • \$\begingroup\$ What are you going to do about requiring a context in the presenter in the first approach? \$\endgroup\$ – barq Aug 3 '16 at 9:12
  • \$\begingroup\$ I will provide mock view with MockContext \$\endgroup\$ – RooMan Aug 3 '16 at 9:15
  • \$\begingroup\$ I would leave any context or android specifics out of your business logic. Makes it much easier to port the code to another project that is non-android and cleanly separates content from the wrappers and views. \$\endgroup\$ – barq Aug 3 '16 at 13:11
1
\$\begingroup\$

I would also go with the seconds approach. A main goal of having MVP is to separate views from logic and a presenter having a knowledge about particular list implementation is violating Open/Close principle. So if you change your ListView into RecyclerView, you have to refactor presenter too.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.