Rich Newman

February 26, 2008

Model-View-Presenter: Variations on the Basic Pattern (Introduction to CAB/SCSF Part 24)

Introduction

Part 23 of this series of articles described the basic Model-View-Presenter pattern (MVP).

This article examines the Model-View-Presenter pattern in more detail. It describes some variations on the basic pattern, and looks at the advantages and disadvantages of using the pattern.

Part 25 of this series of articles will examine how the Model-View-Controller pattern is implemented in the Smart Client Software Factory (SCSF).

Can the View Update Itself? Active View versus Passive View

The version of Model-View-Presenter described in part 23 has an ‘active View’. This means that the View can update itself directly from the Model (arrows C and D on the diagram in the article). As described in part 23, the View can also be updated by the Presenter.

An alternative to this is what Martin Fowler calls the ‘passive View’. Here the View cannot update itself directly from the Model. The only way the View can be updated is via the Presenter. This is the pattern that the Microsoft SCSF documentation describes as Model-View-Presenter.

Diagrammatically this looks as below. It’s identical to the diagram in part 23 except that there are no arrows between the Model and the View:

mvppassiveview.jpg

The passive View design leads to more code in the Presenter and more code in general as the View now has to expose everything that can be updated on its interface, and the Presenter has to be coded to update it appropriately. However, this is arguably a less complicated design than the original active View in part 23.

Does the View Update Automatically? Active Model-View-Presenter versus Passive Model-View-Presenter

As with Model-View-Controller we have a distinction between an ‘active’ and a ‘passive’ design overall (see the section ‘Active and Passive MVC’ in part 22). Model-View-Presenter as described above in part 23 is ‘active’ Model-View-Presenter. This means that if the Model changes all Views will be updated automatically via the eventing mechanism. These events may be sunk in the Presenter or the View.

It is also possible to set up ‘passive’ Model-View-Presenter. This is a slightly simpler pattern where the Model does not raise an event when it changes. This means the View is not updated ‘automatically’. Instead the View is updated when the user next requests it (by pressing a ‘Refresh’ button for instance). At this time either the View or the Presenter will go to the Model to get the new data.

Advantages of Model-View-Presenter

As with Model-View-Controller, Model-View-Presenter has the advantage that it clarifies the structure of our user interface code and can make it easier to maintain. Not only do we have our data taken out of the View and put into the Model, but also almost all complex screen logic will now reside in the Presenter.

This solves the problems with more traditional user interface designs as described in the last few articles. However, it comes at the cost of some complexity.

Since we now have almost no code in our View apart from screen drawing code Model-View-Presenter also makes it theoretically much easier to replace user interface components (user controls, whole screens, or even the whole user interface (Windows Forms to WPF for example)).

In addition unit testing the user interface becomes much easier as we can test the logic by just testing the Presenter. However see part 23 for some comments on whether this is strictly necessary.

Disadvantages of Model-View-Presenter

The disadvantages of Model-View-Presenter are similar to the disadvantages of Model-View-Controller as described in part 22:

  • The pattern is complex and may be unnecessary for simple screens.
  • The pattern is one more thing to learn for busy developers: there’s some overhead.
  • It can be hard to debug events being fired in active Model-View-Presenter.
  • The ‘Passive View’ version of Model-View-Presenter can lead to a certain amount of boilerplate code having to be written to get the interface into the View to work.

My personal view is that even if you think this is a useful pattern (and it is) you shouldn’t use it indiscriminately on every screen in your application. You should use it where you have reasonably complex logic which will benefit from splitting the user interface classes in this way.

User Events and View Logic Combined in the Presenter

One thing that seems a bit odd with Model-View-Presenter is that we have factored both the responses to user input events and what I’m calling the ‘complex view logic’ into our Presenter. At first glance these seem to be slightly different things: perhaps we should have separate classes for each? Perhaps we need a Presenter and a Controller?

One reason for not doing this is that our user interface is getting very complicated if we have both Presenter and Controller.

Also, in the passive version of Model-View-Presenter we may want the user event itself to call the complex view logic and to directly update the View. This means that the code to handle the user event also needs to contain the view logic. It can’t do this if we have separate classes for the two pieces of functionality. In this case it makes more sense if we only have one class.

However, splitting the Presenter into two classes may be a valid pattern in active Model-View-Presenter. Here the Model will be updated in response to a user event by the Presenter. The Model will then raise an event to the Presenters telling them to update the View for complex view logic. The user event and complex view logic are thus separate in the Presenter and could be split into separate classes. We would probably only want to do this in very complex screens.

Model-View-Controller and Model-View-Presenter Confusion

As Martin Fowler points out, there’s a lot of confusion over what Model-View-Controller is. As already discussed, this arises because it doesn’t really apply to modern user interface programming languages in its purest Smalltalk form.

Equally there seems to be a lot of confusion over what Model-View-Presenter is. Martin Fowler currently calls the basic MVP pattern that I describe in part 23 ‘Supervising Controller’. He calls the amended version presented in this article ‘Passive View’ (as does this article).

I’m not quite sure why Mr Fowler calls the basic Model-View-Presenter pattern ‘Supervising Controller’ and not ‘Supervising Presenter’. It seems to me that the key difference between Model-View-Controller and Model-View-Presenter is that the Presenter in Model-View-Presenter can update the View directly. This is not permitted in Model-View-Controller; here the View updates itself from the Model. In the ‘Supervising Controller’ the Presenter/Controller can update the View directly.

Having said that I’m not sure that Mr Fowler would recognize the pattern described in part 22 as Model-View-Controller: this is closer to Model-View-Presenter as he describes it. As I mention in part 22 the pattern described is not ‘pure’ Model-View-Controller because the user events are initially sunk in the View (which is normal with modern UI widgets) and because there’s only one Controller and View per screen, rather than one per widget as in pure Model-View-Controller.

Finally note that I have adopted the ‘Passive View’ nomenclature in this article. However personally I think calling this pattern ‘Passive View’ adds to the confusion surrounding Model-View-Presenter. We already have the concept of active/passive Model-View-Controller and Model-View-Presenter as a whole, ‘active’ being the case where all Views get updated automatically on a change in the Model, ‘passive’ being where they have to update themselves. This is easily confused with an active/passive View distinction. Here an ‘active’ View is one that can update itself from the Model, whether automatically or not.

Conclusion

We have now covered quite a lot of the theory behind both Model-View-Controller and Model-View-Presenter.

Part 25 of this series of articles will show how we can use Model-View-Presenter in the CAB/SCSF using an SCSF Guidance Automation Pattern.

References

The two flavours of Model-View-Presenter described by Martin Fowler
http://www.martinfowler.com/eaaDev/PassiveScreen.html (‘Passive View’ in fact)
http://www.martinfowler.com/eaaDev/SupervisingPresenter.html (‘Supervising Controller’ in fact)

Martin Fowler overview of GUI Architectures, including Model-View-Controller and Model-View-Presenter
http://www.martinfowler.com/eaaDev/uiArchs.html

Good explanation of Model-View-Presenter, Passive View and Supervising Controller on CodePlex
http://www.codeplex.com/websf/Wiki/View.aspx?title=ModelViewPresenterPatternDescription&referringTitle=MVPDocumentation

MSDN Article with code example (although the article is a little confusing)
http://msdn.microsoft.com/msdnmag/issues/06/08/DesignPatterns/

See also the page in the Smart Client Software Factory documentation on Model-View-Presenter
http://www.codeplex.com/smartclient/Release/ProjectReleases.aspx?ReleaseId=5027

February 25, 2008

Model-View-Presenter: Why We Need It and the Basic Pattern (Introduction to CAB/SCSF Part 23)

Introduction

Part 22 of this series of articles looked at the Model-View-Controller pattern and discussed how it is one way of structuring a user interface to avoid having too much code behind a screen.

This article will examine some of the shortcomings of Model-View-Controller, and describe an alternative, which is Model-View-Presenter.

Part 24 of this series of articles will then briefly examine some variations on the basic Model-View-Presenter pattern described here, and look at the advantages and disadvantages of the pattern.

Part 25 of this series of articles will look at the support that CAB/SCSF gives us for the Model-View-Presenter pattern.

Model-View-Controller Problems

There are a couple of user interface scenarios that are difficult to handle with the Model-View-Controller pattern. The first of these is the one that is most widely cited as a problem with Model-View-Controller, but in my opinion the second is the more difficult case to deal with, in spite of the fact that it’s hardly an unusual scenario:

1. Elements of our screen display depend on complex business logic

The canonical example here is coloring the background of a field in varying colors depending on the output from some business rule.

For example suppose we are showing daily sales figures for a business. We might want to color the background of a sales figure green if that figure is more than 10% above the average daily sales figure for the quarter, and color it red if it’s more than 15% below the average. Otherwise we leave the background white.

Model-View-Controller struggles with this scenario. Clearly it involves calculations involving business logic (averaging the sales figures for the quarter). In the Model-View-Controller pattern the business logic should go in the Model class. However, the only place we can sensibly put the coloring logic is in the View when it refreshes itself. We’ll come back to this below.

Note that we want to be able to enter the daily sales figure and have the background color change appropriately depending on the new value.

2. Elements of our screen display depend on what the user has selected in other screen components in a complex way

This could be as simple as a Save button being enabled only if the user has actually changed something on the screen (and being disabled again if the user changes the screen back to its original values).

Again the only place we can logically put this sort of logic in the Model-View-Controller pattern is in the View when it refreshes itself.

Whilst these problems are slightly different they can both be thought of as complex view logic surrounding the state of the user interface.

Why is Putting View Logic in the View a Problem?

In both of the examples above there probably isn’t all that much code relating to our view logic, and maybe putting it in the View in a Model-View-Controller pattern will be fine. However, with complicated screens this ‘view logic’ can run to many hundreds of lines of code. We don’t really want this code in our View, which we want to just be simple screen drawing code. Part of the idea of splitting out the View, after all, is that it becomes so simple we can easily replace it if we want to change our screen technology.

Another problem with having this logic in the View is that the event model may get quite complex. In my example it’s possible that a change in a sales figure that we’re not actually displaying could affect the background color of the textbox. Remember that we are comparing the textbox contents to the average daily sales. If the average daily sales change sufficiently we may need to raise an event to force a color change.

There’s another reason why developers prefer to get this ‘view logic’ out of the actual View class. It can be hard to automatically unit test a View class. Screen widgets often don’t lend themselves to unit testing. If the view logic is in another class it may be easier to unit test it.

Aside on Unit Testing in User Interfaces

I think the difficulties of unit testing user interfaces in Microsoft world are hugely exaggerated. Most Microsoft controls will let you do programmatically almost anything you can do with a mouse and keyboard. So, for example, we have a PerformClick method on a button, and settable SelectedIndex and SelectedItem properties on a ListBox. We can instantiate our screen in the test and interact with it programmatically in the same way we would if we were clicking on things. We have extensive unit tests that work this way in our current project.

It’s true that interactions between controls can be difficult to test (e.g. drag-drop operations). Also third-party (non-Microsoft) controls often don’t expose mouse and keyboard actions in the same way. However, in general you can usually unit test a user interface fairly extensively without recourse to restructuring your code as outlined in this article.

The Presenter in Model-View-Presenter

The first thing to understand about Model-View-Presenter is that it is very similar to Model-View-Controller, only with the Controller replaced with a Presenter (predictably).

The idea of the Presenter is that it can update the View directly. This isn’t permitted for a Controller in Model-View-Controller. This means we can put our complex ‘view logic’ described above into the Presenter and take it out of the View. Clearly we couldn’t do this with the Controller in Model-View-Controller since it had no easy way of updating the View with the results of the view logic: the View updated itself from the Model and the Controller was not involved.

Note that the Presenter, as with the Controller in Model-View-Controller, handles user events raised from the View as well. This means the View only contains screen drawing logic, which is what we want.

So a Presenter is able to ‘present’ data: it can directly update the View. On the other hand a Controller only controls: it takes user input and updates the Model as appropriate. Note that the Presenter is doing some controlling as well since it handles user events.

Diagram of Model-View-Presenter

Diagrammatically this looks as below:

mvp.jpg

As you can see, we again have three classes that interact. As with Model-View-Controller the Model class contains the data to be displayed, and the View class contains the code that actually draws the screen. We have already discussed the Presenter.

As with Model-View-Controller we can have multiple Presenter/View pairs of classes interacting with the same Model (with a change entered on one screen updating other screens showing the same data).

Class Interaction (active Model-View-Presenter with an active View)

When a user interacts with the View an event will be raised. This will be passed immediately to the Presenter (A). The Presenter will update the Model as appropriate (B): it may go back to the View to get the data it needs (F). The Model may at this stage raise an event that gets sunk in the View (C), leading to the View updating itself from the Model (D).

So far everything is the same as in active Model-View-Controller (except with the Controller replaced with the Presenter).

The difference is that when the Model is updated by the Presenter it may raise an event that also gets sunk back in the Presenter itself (E). The Presenter may then apply the complex view logic to work out what needs to be displayed before updating the View (F).

So in this version of Model-View-Presenter the View can update itself directly from the Model in simple cases where there is no view logic. When some view logic is needed the Presenter intervenes. It handles that logic and updates the View directly.

Interface on the View (F)

Another point to note here is that the Presenter accesses and updates the View through a clearly-defined interface on the View (F in the diagram). This has two effects. Firstly we can replace the View more easily with another screen technology since we know exactly what methods need to be exposed (those in the interface). Secondly this makes automated unit testing simpler. We can test the Presenter without needing screen elements directly by mocking the interface on the View in another class.

Conclusion

This article has described a basic Model-View-Presenter pattern and contrasted it with Model-View-Controller. It has examined why we need a different pattern to Model-View-Controller.

Part 24 of this series of articles will examine some variations on the Model-View-Presenter pattern described here, including the one in the Microsoft documentation for the SCSF. It will also discuss some of Martin Fowler’s user interface patterns that are relevant. References to articles for part 23 and part 24 will be given at the end of part 24.

February 23, 2008

Model-View-Controller Explained (Introduction to CAB/SCSF Part 22)

An Apology, and Topics Still To Be Covered

Let me start by apologizing to all the CAB/SCSF fans (?) out there who have been asking me to continue the series of posts. I know it’s been a while since I wrote about the CAB/SCSF (I got diverted by FpML as you can see). However the series of articles is not yet finished and I will be sporadically posting on the topics many of you have been asking about. If there’s interest I may look at how to use some of the other application blocks with the CAB as well.

If there are specific things you would like to see covered please leave a comment.

Having said that, our CAB project is live and working well, and we are moving onto other issues, so my enthusiasm for spending my Saturday mornings writing about CAB/SCSF has waned somewhat.

Introduction

Part 21 of this series of articles briefly discussed foundational modules and the way constants are handled in an SCSF project.

Part 23 of this series of articles will examine another Smart Client Software Factory Guidance Automation pattern, the Model-View-Presenter.

By way of preparation for part 23, this article discusses the problems with putting code directly behind screens in smart client applications, and a traditional solution to this, which is Model-View-Controller.

The Basic Problem

When writing user interface code it’s quite easy to put too much logic in the class that draws a form or user control.

In badly-designed .Net applications, for example, it’s not uncommon to see classes behind user controls of several thousand lines of code (excluding the automatically generated code). We may have code that handles events, updates the data on the screen, caches and refreshes data, updates the state of user interface controls based on the data or user input, colors parts of the screen based on the data, binds data to controls in complex ways and so on.

With all this code in one class it can be difficult to work out what is going on. The code becomes hard to maintain.

Clearly if we have a lot of code doing different things in a class we are violating the single responsibility principle. We should be looking to refactor in such a way that we have a number of classes, each with a clear role and tidy interfaces into the other classes.

The difficulty with this is that it isn’t necessarily easy to see how to break up this sort of code in a logical way. There are a number of user interface patterns that address this. The granddaddy of them all is Model-View-Controller (MVC), although as we shall see this is not a pattern you are likely to see in a .Net application, at least in its original pure form.

Where to Cache the Data

It’s arguable that the main problem Model-View-Controller solves is that of data being cached directly behind a screen and not elsewhere in the application. Again this is a common problem in poorly written smart client applications.

Suppose we have a screen that displays data that has been retrieved into a series of textboxes directly from a middle-tier service. This data is loaded into the textboxes the first time it is displayed, retained in the textboxes but not actually stored in any variables anywhere. There may be a ‘refresh’ button that lets us reload the data from the service. However, the values in the textboxes will not automatically update if there’s a change server-side.

Suppose we now want to add another screen that uses that data in some calculations. Where does the second screen get the data from? If it goes back to middle-tier service the data may be out of sync with the data displayed in the screen. Should it go to the screen itself?

Model-View-Controller (MVC)

The traditional solution to this problem is to use the Model-View-Controller pattern (MVC).

MVC dictates that we have three classes for user interface display:

  1. A Model class contains the data to be displayed. This can be a simple data cache, although it may be a full domain model (classes containing data plus associated business functionality).
  2. A View class that contains the screen code. This would be a user control or form in .Net.
  3. A Controller class that provides the glue between the Model and the View. This class is a little more difficult to understand than the other two. The idea is that the Controller handles all user input, which means events raised in response to user actions (e.g. clicking a button, changing a value in a textbox etc.). It then updates the Model as necessary.

Note that the Controller does not update the View. It updates the Model. If necessary the Model will then raise an event saying that it has changed. The View will subscribe to this event and redraw itself, getting the new data directly from the Model. Note that this is the Observer design pattern: the View(s) observe the Model.

In its purest form the View class should ONLY contain code that draws to the screen: it shouldn’t contain any event handling code for user events, all of which should be in the Controller. This isn’t the usual pattern with a .Net user control of course, where your event handlers are normally in the code behind the user control (the View).  It’s possible to set up the event handlers actually in the Controller, or to just immediately call the Controller from the View in the event handler.

Class Interaction in Model-View-Controller

These classes should have references to each other as shown in the diagram below:

mvc.jpg

The solid arrows above represent references between classes through which direct method calls can be made.

The View class will have a reference to the Model to allow it to directly request the data it needs to display (A).

The Controller will have a reference to the Model because it will need to manipulate it in response to user actions (B). The Controller also has a reference to the View because it may need to retrieve values that have been changed in order to manipulate the Model in an appropriate way (C).

Note however that the Controller will not update the View directly. The View itself will go to the Model to actually get the data.

The dotted lines above represent an indirect relationship where events can be raised from one class into the other. So the Model may raise events when its data changes, which the View will sink and update any display depending on that data (D).

Note that the Model has no direct reference to the other two classes: it is independent of any Views or Controllers.

Use Case Examples

It can be difficult to understand exactly how this fits together when we see it for the first time. In particular what the Controller does can be confusing.

To clarify this here is a use case example:

  • A user interacts with a screen displaying data (which is the View). Suppose that they change some base data and hit an Update button. Further suppose that they expect some derived data on the screen to change as a result of this action.
  • The click event for the Update button gets raised in the Controller. A parameter to the event may be the data that needs to be saved (otherwise the Controller can go back to the View to get it). The Controller takes the changed data and updates the Model for the changes. This will include updating any derived data.
  • The Model raises an event that it has changed.
  • The View will sink the event and redraw itself based on the new data. This means that the correct derived data will now be displayed.
  • The system waits for further user input when the cycle above will be repeated.

Solving the Data Caching Problem

MVC gives a solution to the data cache problem outlined above. We have separated the data for our screen into a Model class. Any other screen that needs to display the same data can access the same Model class (using its own Controller). The textboxes on the screens are effectively just views of this data whenever they are displayed.

As a result if the data changes it should only need to be changed in the one place (the Model) for the individual screens to be able to use it. What’s more, because the Model raises an event when the data changes, ALL we need do is change the data in the Model and all the screens will automatically update. If we change a value in a textbox on one screen it should update on any other screens via the process described in ‘Use Case Examples’ above.

Note that this means that one Model can be associated with multiple Views and Controllers. However, it is usual to have a one-to-one mapping between Views and Controllers: each View will have its own unique Controller class.

‘Pure’ Model-View-Controller

The Model-View-Controller pattern described in this article is one that could be used with modern programming languages such as .Net. The description here is what is usually meant by ‘MVC’ these days. However, MVC as described here differs slightly from the original pure MVC design.

MVC originated with early Smalltalk which was a very different language from modern user interface languages like .Net or Java. For a detailed look at the history of MVC (and of MVP) see Martin Fowler’s article ‘GUI Architectures’.

In the original Smalltalk design every single control (textbox, button, etc.) would have its OWN View and Controller class, and the screen they were on would have a top-level View and Controller that would handle putting them all together. This was because Smalltalk didn’t have draggable user interface controls in the way we do today, so writing a user interface was a somewhat different proposition.

Clearly we could do this in a modern programming language such as .Net, but it would arguably make our code less clear rather than clearer.

Active and Passive Model-View-Controller

MVC as described here is ‘active’ MVC. This means that, as we have seen, if the Model changes all Views will be updated automatically via the eventing mechanism.

It is also possible to set up ‘passive’ MVC. This is a slightly simpler pattern where the Model does not raise an event when it changes, and consequently the View cannot update itself ‘automatically’. Instead the View is updated when the user next requests it (by pressing a ‘Refresh’ button for instance). At this time the View will go to the Model and get the new data.

Advantages of Model-View-Controller

MVC obviously has the advantage that for complex screen logic we get clearer code, which should be easier to maintain. In theory this pattern also makes it easier for us to replace the user interface itself, since only screen logic is in the screen.

MVC also provides an easy way of allowing multiple views of the same data to always be synchronized (via the event mechanism).

Disadvantages of Model-View-Controller

Of course, there’s one obvious argument against using MVC for every single screen in a system: it’s a fairly complex pattern, and for very simple screens may simply mean we create three classes where we only need one. Also you clearly have to learn the pattern to be able to use it effectively, which is an overhead.

MVC also suffers from the same problem that all eventing mechanisms have: it can be hard to debug. When the Model fires an event saying it has changed it may not be immediately obvious where this event is being sunk, and finding out in order to debug the code may be tricky.

However, the biggest problem with MVC is that it doesn’t actually solve all of the issues involved in the original problem described in this article. There are multiple reasons why we might have too much code behind our screens, and for some of these it’s not clear how MVC helps us. For this we may need a slightly different pattern, which might be the Model-View-Presenter pattern the SCSF gives us.

This will be discussed at greater length in part 23 of this series of articles.

Conclusion

Model-View-Controller is a pattern that can be used to structure the code in a user interface in a logical way, and prevent too much code being in the screen class itself. In particular it splits the data for a screen into a separate class.

However, it doesn’t solve all our user interface coding problems as we shall see in the part 23 of this series of articles. For this reason it’s not all that common in modern .Net applications.

References

Martin Fowler on MVC and MVP
http://www.martinfowler.com/eaaDev/uiArchs.html

MVC was originally designed for Smalltalk
http://st-www.cs.uiuc.edu/users/smarch/st-docs/mvc.html

Microsoft on MVC
http://msdn2.microsoft.com/en-us/library/ms978748.aspx

Table of Contents: Introduction to using Financial Products Markup Language (FpML) with Microsoft .NET Tools

Part 1 Introduction

An overview of how we can use Visual Studio to examine the FpML XSDs. Shows how to create a Visual Studio project containing the FpML schemas, and how to use that to navigate through them. Also shows how to validate the XML examples that are provided in the FpML download, both using Visual Studio and in C# code.

Part 2 How FpML Validates A Basic Trade Document

Looks at the structure of an FpML trade document in some detail. Explains how the FpML schemas fit together to validate such a document, and examines the use of base and extension types, and of substitution groups, in the XSDs.

Part 3 Generating .Net Classes From The FpML XSD Schema

Shows how to generate .Net classes in C# from the XML schema documents using Xsd.exe.  Explains how to load data into these classes from an FpML document using C# code, and to save the document back out again from the classes.

Part 4 Problems With Using Xsd.exe To Generate .Net Classes From The FpML XSD Schema

Goes through some of the problems with the C# code generated in part 3, and discusses how to fix them.

The Shocking Blue Green Theme. Create a free website or blog at WordPress.com.

Follow

Get every new post delivered to your Inbox.

Join 83 other followers