More Thoughts on Model View Presenter

This is a follow up to my post on the Model View Presenter pattern with ASP.Net to address or clarify some of comments from the earlier post.  I apologize for being so slow in answering the comments.

The Presenter is a GoF Mediator

Carlton commented that the Presenter class looks a lot like the Gang of Four “Mediator” pattern.  He’s absolutely right.  Something to keep in mind when learning to apply design patterns is that a class or group of classes can easily be an instance of more than one pattern.  In this case “Presenter” or “Controller” is just a more specific name for a class within a larger structural pattern.

Unit Tests Aren’t Enough

MVP certainly makes unit testing easier, but don’t forget to create white box integration tests as well.  The unit tests should remove most of the problems, but only integration tests will reveal all of the defects in the code.  Conventional wisdom says to write automated tests just under the skin of the user interface.  Our experience with writing integrated FitNesse tests against the Presenter classes with live services but a stubbed view has been positive.  You could also write integrated tests that use the real view and the Presenter but mock or stub the backend to fully test the presentation.  Sooner or later you’ll have to do a full end-to-end test, but I think it’s vastly easier to diagnose and fix defects with smaller white box tests first.

Exposing the Model

Harris Boyce‘s colleague didn’t like the view class having a reference to the actual Model (WorkItem) object in the following:

	// Abstracted interface of the WorkItem View screen
	public interface IWorkItemView
	{
		// Packs the user input into a new WorkItem class
		WorkItem WorkItem{get;}

		// Sets the values in the dropdown list for the WorkItem assigned to user
		string[] AssignmentList {set;}

		// Sets the values in the dropdown list for the WorkItem categories
		string[] CategoryList {set;}
	}

It’s a valid objection, but let me try to clarify what I was worried about here.  One of the ways to bog down with the MVP pattern is to make the view interface way too chatty with far too many getters and setters like this:

	public interface IWorkItemView
	{
		string AssignedTo {get; set;}
		string Category {get; set;}
		string Description {get; set;}
		string Priority {get; set;}
		string Comments {get; set;}
		
		/* More properties */
	}

In this case the Presenter starts to become way too busy with pushing data back and forth between the view getter/setters and the Model objects. One of the strengths of .Net user interface development is the strong support for databinding.  I know it’s far from perfect, but it still saves some grunt work and frees the Presenter up to concentrate on flow logic.  I can understand some apprehension about exposing a Domain Model object to a presentation class, so here’s some alternatives to consider:

  • The “Model” doesn’t have to be a Domain Model class.  You can create a custom Data Transfer Object (very appropriate if there is a web service in the mix) or even a lowly DataSet to be the dedicated “Model” and keep your business logic fully encapsulated from the presentation layer.  We actually create DataSet’s from our domain classes for this very purpose.
  • I’m not entirely sold on it, but take a look at Martin Fowler’s Presentation Model pattern as an alternative to MVP.  I’ve used it successfully for complex TreeView operations and the typical “sort/filter/page” operations in every grid reporting page.  I’ll post more on that soon.
  • You can happily use more than one Presenter per View.  One Presenter might handle the low level mapping from the Model to the View and input validation while a second Presenter deals with the flow logic and the backend services.

Constructing Deep Object Graphs

Michael asked how we handle the creation and assembly of deep dependency chains (but he answered his own question).  The presenter needs a reference to the view and the backend services, which probably have dependencies of their own.  Here’s a representative case.  A Presenter class has a dependency on IView, IUserInformationStore, and IServiceFacade.  The concrete class ServiceFacade that implements IServiceFacade has its own dependency on IDomainRepository

	public class Presenter
	{
		private readonly IView _view;
		private readonly IUserInformationStore _userInformationStore;
		private readonly IServiceFacade _service;

		public Presenter(IView view, IUserInformationStore userInformationStore, IServiceFacade service)
		{
			_view = view;
			_userInformationStore = userInformationStore;
			_service = service;
		}
	}
	
	public class UserInformationStore : IUserInformationStore
	{
		public UserInformationStore(string domainControllerName){}
	}

	public class ServiceFacade : IServiceFacade
	{
		private readonly IDomainRepository _repository;

		public ServiceFacade(IDomainRepository repository)
		{
			_repository = repository;
		}
	}

	
	public class DomainRepository : IDomainRepository
	{
		private readonly IDataSession _session;

		public DomainRepository(IDataSession session)
		{
			_session = session;
		}
	}

	public class DataSession : IDataSession
	{
		public DataSession(string connectionString)
		{
			
		}
	}

I’m a huge fan of using Inversion of Control/Dependency Injection to promote looser coupling and better testability, but the responsibility of attaching dependencies has to go somewhere.  We obviously don’t want the ASPX page that creates the Presenter class be responsible for creating the entire object graph of dependencies like the sample below.

	public class View : Page, IView
	{
		private Presenter _presenter;

		public View()
		{
			// Absurd example
			_presenter = new Presenter(this, 
				new UserInformationStore("TheNameOfTheDomainController"), 
				new ServiceFacade(
					new DomainRepository(
						new DataSession("a connection string"))));
		}
	}

I would suggest one of two solutions.  The simpler, but less powerful solution is to use “greedy” testing constructors to attach mock objects in tests, but use a default no argument constructor when a class is created in production code.

	public class Presenter
	{
		private readonly IView _view;
		private readonly IUserInformationStore _userInformationStore;
		private readonly IServiceFacade _service;

		// "Greedy" unit testing constructor only!
		public Presenter(IView view, IUserInformationStore userInformationStore, IServiceFacade service)
		{
			_view = view;
			_userInformationStore = userInformationStore;
			_service = service;
		}

		// Default constructor
		public Presenter(IView view) : this(view, new UserInformationStore(), new ServiceFacade())
		{
		}
	}

The second and more powerful solution is to use a Dependency Injection tool like StructureMap to create the object graphs and attach all of the dependencies. My colleagues frequently snicker that my answer to most design challenges is to use StructureMap, but this case is exactly what I built it for. 

	public class View : Page, IView
	{
		private Presenter _presenter;

		public View()
		{
			_presenter = new Presenter(this);
		}
	}

	public class Presenter
	{
		private readonly IView _view;
		private readonly IUserInformationStore _userInformationStore;
		private readonly IServiceFacade _service;

		// "Greedy" unit testing constructor only!
		public Presenter(IView view, IUserInformationStore userInformationStore, IServiceFacade service)
		{
			_view = view;
			_userInformationStore = userInformationStore;
			_service = service;
		}

		// Default constructor
		public Presenter(IView view)
		{
			_view = view;

			// Use StructureMap to create the object graphs for UserInformationStore and ServiceFacade
			// with all of the necessary connection string and domain controller configuration
			_userInformationStore = (IUserInformationStore) ObjectFactory.GetInstance(typeof(IUserInformationStore));
			_service = (IServiceFacade) ObjectFactory.GetInstance(typeof(IServiceFacade));
		}
	}

Using StructureMap to wire up the dependencies allows for far more flexibility to mix and match the application configuration.  For example, by my team uses StructureMap to switch our web application from using certificates for authentication to a stubbed security mode on our developer boxes by a simple change in the StructureMap configuration.  We also use StructureMap to turn encryption off for easier debugging, stubbing the database, and switching from an installation where the application runs on two physical tiers in production mode to a testing mode where the entire application runs inside a single AppDomain for easier debugging and faster tests.  Here’s a more detailed example of using StructureMap. I’ve mostly used StructureMap for creating pluggable MVP architectures with WinForms applications, but I don’t see why it wouldn’t be applicable for web applications as well.

About Jeremy Miller

Jeremy is the Chief Software Architect at Dovetail Software, the coolest ISV in Austin. Jeremy began his IT career writing "Shadow IT" applications to automate his engineering documentation, then wandered into software development because it looked like more fun. Jeremy is the author of the open source StructureMap tool for Dependency Injection with .Net, StoryTeller for supercharged acceptance testing in .Net, and one of the principal developers behind FubuMVC. Jeremy's thoughts on all things software can be found at The Shade Tree Developer at http://codebetter.com/jeremymiller.
This entry was posted in Design Patterns, StructureMap. Bookmark the permalink. Follow any comments here with the RSS feed for this post.
  • Martin

    I’m a big fan of using DI to loose the dependency of the components and implementing MVP with DI I steped with a problem that I had to solve in a way I did not like that much and its that :

    In Mosts MVP implementations, the View news his own Presenter, passing this to the constructor.
    Using DI the PRO is that you dont have to new up the Presenter into the view, you can just inject him via Constructor that would give lot of benefits because frecuently the one that has many services proxys and components into is the presenter, the view should only have the Presenter injected.
    In that situation you fall into a circular dependency problem that I had to solve removing the View from Presenter’s Constructor and Set it up via Method that has to be called in the very View constructor … of course I dont like it very much .. What do you think about it ?

  • Nicolás

    Jeremy, how do you manage diferents views opened. for example in a MDI winform application with dialogs. How could we refresh all the related views?
    For example when we have form with a list and a dialog to create or edit.

    Thanks.

  • http://codebetter.com/blogs/jeremy.miller Jeremy D. Miller

    Mohammad,

    You commented on a different post, and I don’t have an answer yet;-)

  • Mohammad Azam

    Was my post deleted??

  • aviad

    Vk,

    the link bellow has C#2.0 WinForms case study for MVP.

    http://aviadezra.blogspot.com/2007/07/twisting-mvp-triad-say-hello-to-mvpc.html

    Hope that helps,

  • Vk

    I knw its too late to ask about this but did you get chance to develop an example on WinForms specific example. I have to develop one with multi-threading and I’m not quite sure where to thread from

    thanks

  • Alex

    Jeremy, really appreciate your work on the MVP but having an issue with the whole multiple data services of a presenter. I have a very simple view which requires data from methods of 2 distinct web services. These web services are well established and I cant change the methods of either so how do I pass in a single service interface to the presenter?

    I realise I could create a single service interface which implements both methods but I am then left with the prospect of creating another web service which will have duplicate methods of the 2 existing web services.

    Very grateful for your ideas or those of others.

  • http://chrisdonnan.com/blog chris donnan

    FYI – I am working the Spring.net desktop app framework. (DAF) browse the CVS – It has yet-another-take on MVP. DAF work is only in the sandbox area of the CVS – but it is all related to this stuff…..

    http://springnet.cvs.sourceforge.net/springnet/Spring.Net/sandbox/src/Spring/Spring.Daf/UIModel/BasicPresenter.cs?view=markup

    start there – check out related commands, actions etc.. My problems w/ standard presenters in the past is that they get ‘fat’. Commands help out here.

    -Chris

    PS – always a good read here :)
    PPS – get latest anon via cvs and build the Daf.Demo

  • CS

    “Cs and Dru, I’ll see what I can do about a WinForms specific example. Anything specific you want to see”

    Well it doesn’t have to be anything too fancy. Maybe a form with a TreeView on the left that updates to a different panel on the right side of them form (that has buttons etc maybe for adding or removing items to a collection?). Maybe a form with a TabControl. Just a couple ideas. Thanks for the great work.

  • Dan

    >Cs and Dru, I’ll see what I can do about a WinForms specific example. Anything specific you want to see?

    While Im not Cs or Dru I do have something specific Id like to see a good example of:

    Loading some data that will take a long time to load (ie, slow running process) and that has results that needs to be displayed in the form. And also with some form of progress bar on the loading with a cancel button. (Its the interaction between the GUI thread and the worker thread, and also how to test that effectively that Im interested in.)

    For instance: When loading up an admin form you need to load a lot of data from the database, but you dont want the program to freeze while loading the form.

    Would be grateful for any input you could give

  • Liang

    Jeremy,

    There has a UI implementation from Jay fields, another ThoughWork. It seems pretty interesting, check it out:
    http://jayfields.blogspot.com/2005/08/view-observer.html

  • Liang

    Very appreciate, Jeremy!

  • Jeremy D. Miller

    Liang,

    Take a look at the “ApplicationController” pattern from Fowler’s PEAA book. Here’s a link –> http://patternshare.org/default.aspx/Home.MF.ApplicationController.

    In effect, create an uber-controller that manages the navigation graph. Make the page presenter/controllers delegate to the ApplicationController for navigation.

  • Liang

    Jeremy,

    I am using MVP in my current project. I create presenter for User Controls, similar like the example you provided. The only difference is I use event call to invoke Presenter logic. But I still have question regarding how to “navigate” the pages? What is the approach you prefer?

    Thanks a lot!!

  • Jeremy D. Miller

    Joe,

    Yes, you could easily have presenter/controller classes that would need to call into multiple backend services. I would probably model the state management as a separate service for instance.

    Here’s the “but” though, if you have a presenter that’s depending on several backend services I’d be suspicious about your class structure. My rule of thumb is no class should need more than 2-3 mock objects in any given unit test.

    You can always create a Facade class to consolidate finer-grained services behind a more coarse-grainted interface. You could also use multiple presenter classes for a single screen to keep each class cohesive.

  • Joe Ross

    Jeremy, Been following lots of your posts and have read and re-read the recent MVP ones. I have a little test app I’m working on while I figure out how we want to structure our code in future releases (ASP.NET app) and have implemented a basic MVP sample successfully. My question for you is on the first MVP/ASP.NET post but it’s only loosely related to MVP. Your WorkItemPresenter class has a ref to the view and a ref to the service. The assumption being that a single service will meet all of the needs of this presenter. Do you have scenarios where a presenter might hook into multiple backend services? Or do all of your services always encapsulate all logic that a consumer might need? For example, your service interface has a method GetAssignmentListForCategory. Imagine you needed this assignment list in other parts of your app that didn’t rely on IWorkItemService. Would you expose this method in multiple services or consume multiple services in certain presenters?

    Thanks and good luck keeping up the informative posts!

  • Jeremy D. Miller

    No apologies necessary Michael, and thanks for the comments. It’s funny, but my wife doesn’t really hold up her end of technical conversations either.

  • Michael

    Sorry, Jeremy. There’s no one around here to talk to about anything technical, and for some reason, my girlfriend doesn’t seem to want to hear it anymore (go figure…). So I bug bloggers ;)

    As to mocks/stubs… it’s just something I’ve found myself getting bitten by. The null/empty list example is a little silly, but I’ve been in situations where I later found out a stub higher up didn’t match an implementation lower down, because they were isolated. This was caught in integration, but I’d prefer early warning. I’d like a tool or pattern that allows me to reuse the applicable portion of the unit tests written for concrete implementations to make sure stubs are behaving correctly as they’re written, not later, and vice versa, to make sure that concrete implementations conform to the stubs you may have already written.

    I’ll have to think more on it. As you mention though, I don’t want to overthink it. If I do end up with a solution, it needs to be somewhat elegant and intuitive. Perhaps I’m just paranoid.

    In any case, my experiences so far with TDD have been great, and I have much more to learn. Your input is appreciated, as always.

  • Jeremy D. Miller

    Michael,

    Dude, you’re making me work a little bit here;) My immediate response to you is to be careful that you’re not over-thinking the issue.

    Even though I’m the creator of a DI tool, I *strongly* believe that the best way to attach a mock/stub object in a unit test is through constructor injection because it makes the dependency relationship more clear. Attaching the mock or stub through a DI config file is a bit of hidden black magic. It’s not that bad if you can do the injection inside the test itself. With StructureMap it would be:

    ServiceFacadeStub stub = new ServiceFacadeStub();
    ObjectFactory.InjectStub(typeof(IServiceFacade), stub);

    or

    ObjectFactory.SetDefaultInstanceName(typeof(IServiceFacade), “Stubbed”);

    or

    IMock serviceFacadeMock = ObjectFactory.Mock(typeof(IServiceFacade);

    Your goal of reusing a testfixture for both unit testing and integration testing might not be feasible. The integration testing most likely requires some additional database or file system setup that the mock objects don’t. I’m going to have to think a bit more about this, but I write integration tests much differently than my unit tests and they don’t completely overlap.

    You also want to keep the tests as self-contained as possible. Both to make the tests standalone and to make the tests as intention-revealing as possible. I want to be able to look at a test in a separate screen. If I have to alt-tab between the test code and configuration files or database views I’m adding to the cognitive overhead of the test.

    I don’t know that you necessarily need to be unit testing the stubs themselves, but you definitely need to writing tests against the ConcreteServiceFacade to make sure that the class behaves the way that the Presenter client expects. This can get into absurd lengths, but the ConcreteServiceFacade can be tested against mocks that represent the lower level services. This mock object can be set up to throw an exception so you can test the error handling behavior of the ConcreteServiceFacade.

    The whole point of a stub or a mock is to create a fixed behavior in your automated unit tests to minimize the number of variables in any given test. The behavior of the mock/stub should be as clear as possible to make the test self-describing. Simply make the stub/mock/fake return null to test how the Presenter deals with the exceptional cases. With NMock you’d have serviceFacadeMock.ExpectAndReturn(“GetListOfWidgets”, null); or serviceFacadeMock.ExpectAndThrow(“GetListOfWidgets”, new ApplicationException(“Really bad error”));

    I’d much rather throw an exception (easy to simulate with a mock object library) than check for nulls, but that’s just me.

    As for a parameterized fixture, I’ve had a lot of success creating little custom assertion classes. You might not be able to reuse the whole test fixture, but you can reuse some pieces. I’d recommend that you harvest reusable pieces from the unit test fixtures once you start the integration tests.

  • Jeremy D. Miller

    Liang,

    I don’t think that there is any single way to structure the namespaces and assemblies, but my preference is to put the IView/Presenter pairs in the same namespace. I generally keep the view classes in the same assembly (we use a class library project for the user controls anyway), just in a specific “Views” namespace.

    I like to divide assemblies based mostly on the physical deployment. I really don’t like unnecessarily granular assemblies. It definitely makes the automated CI builds longer and it just makes configuration management harder.

  • Jeremy D. Miller

    Cs and Dru, I’ll see what I can do about a WinForms specific example. Anything specific you want to see?

  • Michael

    Thanks Jeremy! Great information.

    I’m still pondering testing. I want a way to hold my stubs to the same standards as my production classes.

    For example, suppose you code a Presenter against an IServiceFacade interface. The Presenter calls IServiceFacade.GetListOfWidgets(), and expects null on failure, and your ServiceFacadeStub is coded accordingly to pass the Presenter tests. Some time later, you code the live ServiceFacade against the IServiceFacade interface, and it’s passing it’s tests.

    At this point, you have no guarantee that it’s returning null on that failure condition as the Presenter expects. You might have writen a test that explicitly checks for an empty list instead of null on failure, and everything passes despite the flaw. The Presenter is happy getting null from the ServiceFacadeStub, expecting the real implementation to behave the same, while the ServiceFacade is happy to return an empty list to it’s own test fixture, ignorant of it’s errant ways.

    Your solution rings true, in that a live integration test will likely notice this. However, what if there was some way to a) reduce the effort of duplication between unit tests and integration tests, and b) notice the flaw sooner.

    Two things come to my mind as I write this….

    One is DI for test fixtures, so that you could reuse a single test fixture for both unit tests and integration tests by simply setting up two test environments with different configs, but against the same code.

    Another is some sort of parametized fixture. I’m not sure of the specifics, but some way to execute the same suite of tests writen for a live service against a mock or stub at will. In such a way, the Presenter could pre-test the IServiceFacade stub against the same code writen for the live ServiceFacade. It doesn’t have to be the full-fledged ServiceFacadeFixture, but perhaps something that simply validates that a stub implements behaviors that you want common to all implementations of IServiceFacade, such as predictable failure conditions and return values.

    My goal isn’t to create more work, but to structure things in a way that allows test-reuse and ensures stability of stubs and mocks during unit testing, so errors can be caught sooner.

    Am I off the mark?

  • Liang

    I am wondering how to orgainze the assembly. The Presenter class is in the same assembly with IView, IUserInformationStore, and IServiceFacade?

    Thanks!

  • dru

    Sweet article. +1 for the windows discussion.

  • http://www.UdiDahan.com Udi Dahan – The Software Simplist

    You could also have separate interfaces for your domain objects so that the views wouldn’t depend directly on their implementation.

    There are two perspectives on this:

    1. If the domain only exists on the client side, there are methods in your domain objects that you probably don’t want your view to see/use – so having a separate interface might be a good thing.

    2. If you have two separate domains for your client side and server side, then having the separate interfaces probably isn’t necessary since the methods mentioned above would probably only be available on the server side.

  • cs

    Hi Jeremy,
    I love your articles on MVP. Do you think you could do one on MVP with a WinForms app too please? Maybe something where you combine MVP with some WinForms code and RhinoMock to show some cool testing stuff.