Model-View-Presenter View-Model (MVPVM)

!!NEW!! See authored MSDN article on topic on the following link:
http://msdn.microsoft.com/en-us/magazine/hh580734.aspx

The MVP-VM pattern is the necessary evolution of the Model-View-Presenter pattern for the WPF and Dependency Injection environment.   It is a combination of MVP and MVC’s Application Model (Application Model is also known as Presentation Model and MVVM[1])

MVPVM

Presentation Layer

The Triad components (View Model-View-Presenter) that the user will interface with

Model

The model is your data structures, databases and tables.   These could reside in SQL servers, files or in the cloud.   Where the model structures will be globally available to all layers the actual data is only available via the Data Access Layer (DAL)

Data Access Layer (DAL)

The DAL should be the only interface to your model.   Classes and methods used to access the data will reside at this layer.   Ideally your DALs will have a clear separation of concerns, i.e., only do one job and do it well.  For example a SQL DAL will only process SQL queries, an XML File DAL will process XML queries against files and an XML Web DAL against Web Services as applicable.   DALs will only return object references from the Domain within scope of all layers, i.e. WCF services calls return data that is only within scope of the DAL that is consuming the service, it must transfer this data, via Data Transfer Objects (DTO) to structures within the scope of the application.

It is easy, and quite common, to have your presentation layer access the model directly.   This is not extensible and will require you to update “all” presentation layer components when interface changes occur to the data, i.e., a field is removed.    A DAL is the only layer that is required to know about changes.  For example it could provide dummy data for the field that is no longer used by the system.   Programmers will have to remove references to the field as but it won’t break any of the existing applications that rely on it – the work can be prioritized as applicable.

Business Logic Layer (BLL)

The business logic layer is the only layer that should be consuming your DAL .   It doesn’t concern itself with specifics of data access, e.g., doesn’t care about file connections, SQL statements or XML queries to be executed by the the DAL.   It simply request objects from the DAL based on an established interface (contract).

This is particularly important for Dependency Injection since application configuration could easily swap out a DAL without the BLLs knowledge.  For example your IT team notifies you that it will be swapping out your SQL Server with a Cloud Server in six months.  The current application configuration looks as follows:

       container.Register<IFinanceData, SqlFinanceDal>()

Which the BLL will use as follows:
var financeDal = container.Resolve<IFinanceData>();
       var dataList = fianceDal.GetFinancialDataForGroup(groupId);
var isValid =  ValidateData(dataList, out dataException)
if(!isValid)
throw new InvalidFinancialDataException(dataException);
return dataList;

The “only” code changes that you would have to make would be to point your Unit Test at the new CloudFinanceDal, which will implement the IFinanceData interface, and do TDD until all of your test pass.  Once done your Module configuration would be updated as follows and you would be done!

container.Register<IFinanceData, CloudFinanceDal>()

TRIAD: View-Model, View and Presenter (MVP-VM)

With MVPVM the presenter is responsible for instantiating the view, view model and to populate the view model as required.   The view observes the view model (via data binding) and provides a graphical user interface which represents the state of the view model, i.e., current values of first name, last name, middle initial, etc.  The presenter is allowed to update the view directly with the rule of thumb being if one line of code can prevent numerous lines of complex XAML – to use one line of code.   The view model is a POCO that represents the state of the data and the view.  It solves problems noted with MVC’s Application Model (aka Presentation Model and MVVM) such as having behavior or UI specific properties pollute the domain objects, i.e., visibility and view background color respectively.

Besides reuse against numerous projects, applications, teams and groups there is also the added complexity of multi-targeted enterprise applications.   When your single code base supports the Silverlight, WPF (Desktop) and Windows Phone environment, as is the case with the Password Manager currently under construction at http://PasswordMgr.CodePlex.com.

MVP-VM in Action

The following is from the above noted Multi-targeted application, it is the SecurityModule and will be used to demonstrate MVPVM in action:

ContainerSecurity

In this fictional scenario we have a reusable Security view composed of  the SecurityMainView, SecurityViewModel and the SecurityPresenter triad.   Since it resides in the Gwn.Infrastructures project it is available to an unknown number of applications, teams and groups; only code in the Gwn.PasswordManager.xxxx project is specific to the Password Manager application.

For the next sprint I’m assigned the task of providing a login specific to the Financial group; they will be required to login with their date of birth as well as their login name.   The designer updated the SecurityMainView and SecurityViewModel the last sprint so that if the IsFinancialGroupMember flag is set on the SecurityViewModel the date control field will appear which is bound to the SecurityViewModel.BirthDate field.

I would create a new module loosely comparable to the one shown in the image above and add a call to the applicable BLL so that I could retrieve the security record based on the current system login (the implementation “could be” a ADSUserSecurityDAL), e.g.,

var securityRecord = container.Resolve<IUserSecurityDAL>().GetCurrentUser();
presenter.ViewModel.isFinancialGroupMember =
securityRecord.IsMemberOf(SecGroups.FinancialGroupMember);

I would then update the SecurityPresenter’s  BLL call with an overloaded validate method, so I don’t break existing code, after updating the BLL and DAL as applicable.

Note:  The SecurityViewModel only had two additional properties added and remains un-bloated for the countless other uses of it with no requirement for regression testing as only the new module uses these new features.

  1. ^ PresentationModel and WPF, by John Gossman
Posted in Uncategorized | Leave a comment

Model-View-Controller : Understanding our past to harness the future technologies

Mistakes

Model View Controller (MVC)

Windows programmers generally start learning application development by creating form(s), dropping controls on them and wiring-up the controls events.  The form(s) will consist of a visual component and its associated code which we call “code-behind”.   Where this is convenient for very small applications it doesn’t lend itself to reuse or extensibility.   MVC addressed the issues of reusability and pluggabity with a three way separation of the parts that represent the model of the application domain, the way the model is presented to the user and the way the user interacts with it[8].

Origin

MVC was conceived as a solution to the problem of handling large and complex data sets[6]. Trygve Mikkjel Heyerdahl Reenskaug, a Norwegian computer scientist, created the Thing-Model-View-Editor pattern in 1978 while visiting PARC (Xerox Palo Alto Research Center).   The first implementation had a model, view, controller and editor where the editor was a component created by the view on demand as a interface between the view and the input devices. Thing-Model-View-Editor was later renamed Model-View-Controller.  After Trygve left Xerox PARC, Jim Althoff and others implemented a version of MVC for the Smalltalk-80 class library.  

MVC was not used for Smalltalk-80 in the manner it was originally conceived; Trygve noted that Jim Althoff used the term controller differently then he did; for Trygve the controller was responsible for “creating and coordinating its subordinate views and handled input relevant to the controller/view assembly[6].   Smalltalk-80 defines MVC as follows[8]:

The model of an application is the domain-specific software simulation or implementation of the application’s central structure. This can be as simple as an integer (as the model of a counter) or string (as the model of a text editor), or it can be a complex object that is an instance of a subclass of some Smalltalk-80 collection or other composite class. Several examples of models will be discussed in the following sections of this paper.
Views deal with everything graphical; they request data from their model, and display the data. They contain not only the components needed for displaying but can also contain subviews and be contained within superviews. The superview provides ability to perform graphical transformations, windowing, and clipping, between the levels of this subview/superview hierarchy. Display messages are often passed from the top-level view (the standard system view of the application window) through to the subviews (the view objects used in the subviews of the tool view).
Controllers contain the interface between their associated models and views and the input devices (keyboard, pointing device, time). Controllers also deal with scheduling interactions with other view-controller pairs: they track mouse movement between application views, and implement messages for mouse button activity and input from the input sensor. Although menus can be thought of as view-controller pairs, they are more typically considered input devices, and  therefore are in the realm of controllers.”

MVC Evolved

MVC continued to evolve to solve problems such as separating visual state from domain objects[1] and allowing the model to update the view directly (which contradicts early principles of MVC).   While still being called MVC the underlying responsibilities of the model changed within the Triad; as a result the models name would be changed to Presentation Model or Application Model Martin Fowler, in his GUI Architectures document, describes the Presentation Model which shares most of the same concepts of the Application Model with the exception of being able to update the view directly (which is not part of the Presentation Model).  

Martin Fowler, also states in his GUI Architectures document that “Different people reading about MVC in different places take different ideas from it and describe these as ‘MVC'”[1]; he later states “it’s also the most misquoted (pattern)“.   I contribute the cause of the misunderstandings to modern day developers not having a common core of experience with the early developers/architects; our environments are totally different and many of us have always worked with smart controls (I’ve been programming for over 20 years).

To effectively understand MVC, today’s developers should understand that smart controls made the controller in MVC obsolete.  The authors of “Twisting the Triad” note the following: “the idea of a controller did not fit neatly into the Windows environment. Microsoft Windows, like most modern graphical operating systems, provides a set of native widgets from which user interfaces can be constructed. These “windows” already include most of the controller functionality embodied as part of the underlying operating system control.“.   Martin Fowler states “parts of classic MVC don’t really make sense for rich clients these days”[1]

MVC

MVC doesn’t apply to smart controls since they don’t require a controller (gestures and events are handled by control)

Gestures & events

Before we continue we have to have a clear understanding of what “gestures and events” are within the context of the MVC environment; since our smart controls handle these for us we may not be familiar with these terms and could make assumptions.  Gestures are button clicks, key clicks, selecting a menu-item/Window, etc.  Gestures trigger a function to carry out a task asychronously.  If the program is busy when the gesture occurred it will be put on a queue of events until the application can handle it[5].  With smart controls, gestures and the event loop function are handled for us under the hood; we simply subscribe to events, i.e., Click, MouseDown, etc and point to a method that will handle it. 

WIRE UP

The following paragraphs are an excerpt from the “How to use Model-View-Controller” by Steve Burbeck, Ph.D:

Unlike the model, which may be loosely connected to multiple MVC triads, Each view is associated with a unique controller and vice versa. Instance variables in each maintain this tight coupling. A view’s instance variable controller points at its controller, and a controller’s instance variable view points at its associated view. And, because both must communicate with their model, each has an instance variable model which points to the model object. So, although the model is limited to sending self changed:, both the view and the controller can send messages directly to each other and to their model.
The View takes responsibility for establishing this intercommunication within a given MVC triad. When the View receives the message model:controller:, it registers itself as a dependent of the model, sets its controller instance variable to point to the controller, and sends the message view: self to the controller so that the controller can set its view instance variable. The View also takes responsibility for undoing these connections. View release causes it to remove itself as a dependent of the model, send the message release to the controller, and then send release to any subViews

Because of WPF constraints we can’t follow the conventions used for loading/wiring-up the MVC triad; the following is how WPF can load/wire-up a process:MVC-Sequence
Fig 3.

 

The View

In MVC the view’s responsibility is to display the data held by the model object[2], our view will display the Image and Label from the model while using the IsLabelDisplayed value to determine whether the textblock (under the image) is visible.   The View has knowledge of its model but is loosely coupled (could be tied to any model with these property values); it has no knowledge of our SmileyModel class.   Unlike the model, the controller is unique to its view and visa versa[4] – our SmileyView is tightly bound to our SmileyController (line 13 below).

 

MVC-View
Fig 4.

Above we define the “Template” (our view) for the SmileyController (lines 10-22).   The SmileyController is used in the LeftPanelView and RightPanelView (the two views with Smileys) with the results being show in in the ResultsPanelView (far right view which was added later).  
Below we show the source for the LeftPanelView, note that on line 24 below we instantiating a SmileyController by placing it as an element in the StackPanel. WPF will search for a ControlTemplate, find it above and execute the OnApplyTemplate() method of the SmileyController providing a reference to itself (see code snippet below the following image).   This effectively permits the controller to wire-up the View’s “gestures” so that they can be processed by the SmileyController.

MVC-SmileyControllerUsage

The Controller

Consistent with MVC, our controller’s only responsibility is to handle gestures and events, in our case the gestures will be the mouse hover (icon changed to a hand) and the click event (to start process).  The view/controller’s both know about the existence of the model but not visa versa[2]. 

Figure6
Fig 6

The Model (and Smiley MVC overview)

Below we show the final component of our Smiley triad – the model  which represents the data underlying the object”.  In MVC, the model (Application Model) is responsible for handling application logic, communicating between domain objects and the view/controller[2].  As such, our model holds the application logic for our Smiley triad.   If we wanted to persist the model values so that we could later retrieve them it would be the model that would contain the logic to do so.

If you’ll examine the ImageMouseDown code within the SmileyModel you’ll find that it changes the image, updates the model to reflect the new state and raises the SmileyStateChanged event.   Note that the LeftPanelView is setting the IsTextDisplayed property to False (line 24 of Fig 5.); this will prevent the Smiley state text from showing underneath the Smiley image.  Instead the LeftPanelView will display the content above the image (reference Binding on line 19 of Fig 5.)
Our view is bound to the model and “accesses the data from the model and specifies how the data from the model is drawn on the screen” via data binding.  

The controller processes user gestures (clicks) and changes the underlying data (on the model); the model will then close the loop by notifying the view that it’s state has changed via the NotifyPropertyChanged event.   I should emphasize that the controller only handles gestures and events, you’ll find the Smiley controller has no application logic.

MVC-Model
Fig 7.

MVC Emotion Manager Demo (closing note/point)

So now we have a tri-state smiley control that can be easily reused.  If Microsoft were to come out with a Smiley control our controller would no longer be needed; it would effectively render the Model-View-Controller pattern useless to us.  
The SmileyController’s gestures and SmileyModel application logic would be handled by the new control so all we would have to do is wire-up the new View to a Model that contained the applicable properties.
 

 

VM

Fig 8.

MVC revisited

MVC had issues which had early architects looking for a better pattern.  

  • Smart Controls – made the MVC pattern obsolete
  • Updating the view – in our Smiley triad we had a business requirement to change the background color based on the state of the smiley icon (green=happy, blue=confused and pink=unhappy).   Since the the model, which handles the application logic, has no knowledge of the view it is forced to follow MVC conventions by triggering an event passing the color with it[2].   Our WPF Emotion Manager demo used a Dependency Property which in essence follows that convention.
  • Polluting domain objects – a color is not part of the domain[1] however it has to be on our domain object (model) for processing. 

Both Taligent and the Dolphin Smalltalk teams uncovered the same weaknesses[2] (some noted above) and solved the problem by rotating (twisting) the triad 60 degrees.   MVC would evolve so dramatically that it would now be called Model-View-Presenter (MVP)

 

References

  1. ^ GUI Architectures, by Martin Fowler.
  2. ^ Twisting the Triad, by Andy Bower, Blair McGlashan
  3. ^ MVP: Model-View-Presenter by Mike Potel, the “Potel paper”
  4. ^ How to use Model-View-Controller (MVC) by Steve Burbeck, Ph.D.
  5. ^ An Introduction to GUI Programming with UIL and Motif
  6. ^ MVC Xerox PARC 1978-1979, by Trygve Reeskaug
  7. ^ Models-Views-Controllers, by Trygve Reenskaug
  8. ^ A Description of the Model-View-Controller User Interface Paradigm in the Smalltalk-80 System, by Glenn E. Krasner and Stephen T.Pope
  9. ^ PresentationModel and WPF, by John Gossman

Posted in Uncategorized | Leave a comment