Archive for DesignPatterns

MVVM Compared To MVC and MVPVP


MVVM Compared To MVC and MVP

 

image

MVC – Model View Controller

Let’s look at MVC first. You’ll notice a few things about the diagram:

The input is directed at the Controller first, not the view. That input might be coming from a user interacting with a page, but it could also be from simply entering a specific url into a browser. In either case, its a Controller that is interfaced with to kick off some functionality.

There is a many-to-one relationship between the Controller and the View. That’s because a single controller may select different views to be rendered based on the operation being executed.

Note the one way arrow from Controller to View. This is because the View doesn’t have any knowledge of or reference to the controller.

The Controller does pass back the Model, so there is knowledge between the View and the expected Model being passed into it, but not the Controller serving it up.

MVP – Model View Presenter

Now let’s look at the MVP pattern. It looks very similar to MVC, except for some key distinctions:

The input begins with the View, not the Presenter.

There is a one-to-one mapping between the View and the associated Presenter.

The View holds a reference to the Presenter. The Presenter is also reacting to events being triggered from the View, so its aware of the View its associated with.

The Presenter updates the View based on the requested actions it performs on the Model, but the View is not Model aware.

MVVM – Model View View Model

So with the MVC and MVP patterns in front of us, let’s look at the MVVM pattern and see what differences it holds:

The input begins with the View, not the View Model.

While the View holds a reference to the View Model, the View Model has no information about the View. This is why its possible to have a one-to-many mapping between various Views and one View Model…even across technologies. For example, a WPF View and a Silverlight View *could* share the same View Model. However, my own feeling is that this is a bad practice and creates Franken-ViewModels that have too many responsibilities. It’s better to keep it as a one-to-one mapping instead.

You’ll also notice that the View has no idea about the Model in the MVVM pattern. This is because, as far as the View knows, its “Model” IS the View Model (hence its name). Because of how data-binding and other features like commanding work in WPF and Silverlight, there is rich communication between the View and View Model, isolating the View from having to know anything about what’s really happening behind the scenes.

Model View Presenter (MVP) pattern


Model View Presenter (MVP) pattern


Introduction

MVP pattern is a type of UI design pattern which enables decoupling of the UI logic without UI representation and by that enables treating code base without consideration on presentation technology used.

One of the commonly stated advantages of this approach is that it enables writing of appropriate test scripts to test UI part of application. MVP enables that without the need of using third party tools which scripts user UI actions and which are fairly easy to use for testing simple actions like button click, but to write a user UI scripts for data manipulation of a grid or some more complex layout. All the logic is inside the presenter and the presenter is talking to view only through the interface, so any mock object could be used for testing as long it implements the view interface

Second advantage is the fact that by decoupling code in presenter level we are enabling reuse of the code logic to totally different presentation technologies. For the example, the same presenter can be used without any problem in both Web Form and Win Form worlds, as long as they implement agreed interface

Third advantage is in the fact that in big companies (like the one I’m working in) to implement your supportive UI code, you are often forced to wait on UX (user experience) people to make the web forms and that sometimes is a very long period. Also the way of communication between products, tech leads and developers is quite often based on some word document based FRD which (from developer perspective) is not the most precise way of specifying requirements. MVP is allowing the tech leads to crystallize results of an FRD to a set of interface definition of a view and that interface could be immediate base for developers to start coding , without waiting for anyone knowing very precise what are the requirements. (Who said TDD? 🙂 )

Illustration 1. Logical view of the MVP pattern.

 

Short diagram description

View is responsible for visual representation of the form and it contains a presenter in private field. View is implementing interface whose members are approximated and technology striped UI elements of the view. When some event occurs on view is just forwarding it to presenter and it is presenter responsibility to handle the event. Presenter is manipulating view by talking to interface representation of the view. Presenter should never reference directly view members (UI controls). Presenter for his logic operations is using Model which can be persisted state or representation of the object which provides necessary functionality

Implementation procedure:

Create a view by using standard Visual Studio IDE tools.

For my example I will create first a web form with:

    • a label on top which would show possible validation error
    • Last name, first name, address and a city text boxes
    • Search text box with a button

    Illustration 2. UI look of the view made by web form

    Interface would be created in a separate project called presenter so we could reuse it later to demonstrate usage outside of our web application. Web application should have a reference to the presenter project

    Illustration 3. Project structure  – separating and referencing presenter

    Create a interface as an abstract form of a view with setters only for text boxes (because presenter would fill == set them) and getter property only for searcher (presenter would take that value and perform a search)

    Illustration 4. View interface definition

    namespace Presenter

    {

        public interface IUserView

        {

            string FirstName { set;}

            string LastName { set;}

            string Address { set;}

            string City { set;}

            string ErrorMessage { set;}

            string SearchCriteria { get;}

        }

    }

    After creation of interface we are implementing it on view by setting and getting UI element values in the property

    Illustration 5. View interface implementation

        #region IUserView Members

        public string FirstName

        {

            set { firstName.Text = value; }

        }

        public string LastName

        {

            set { lastName.Text = value; }

        }

        public string Address

        {

            set { address.Text = value; }

        }

        public string City

        {

            set { city.Text = value; }

        }

        public string ErrorMessage

        {

            set

            {

                errorMessageLabel.Text = value;

                errorMessageLabel.Visible = value != “”;

            }

        }

        public string SearchCriteria

        {

            get { return searchCriteria.Text; }

        }

        #endregion


    Creation of presenter class includes creation of a private field of view interface type and overloading of a constructor to accept that view interface

    Illustration 6. Presenter  wiring the view

     namespace Presenter

    {

        public class UserViewPresenter

        {

            IUserView _view;

            /// 

            /// Initializes a new instance of the UserViewPresenter class.

            /// 

            /// 

            public UserViewPresenter(IUserView view)

            {

                _view = view;

                SetCustomerData();

            }

    Presenter would have to implement business logic, which In our example is finding of a customer for a given code. I’ve created Customer.xml file as D:\Customer.XML

    Illustration 7. Exampled data used for sample 

     

    Presenter would implement therefore a method named SetCustomerData which task is to find a customer of a given code and update the view with resulting data. In case the entered code is not a valid number presenter would show appropriate message on validator that there is a syntax error. In case there are no contacts with a given code presenter should empty view and show a message that not existing code has been entered.

    Illustration 8. Implementation of a presenter logic 

    public void SetCustomerData()

    {

    int searchCode;

          bool isValid = int.TryParse

                (_view.SearchCriteria, out searchCode);

    if (isValid)

          {

                using (DataSet ds = new DataSet())

                {

                      string filePath=string.Format(

    “{0}Customers.xml”,

    AppDomain.CurrentDomain.BaseDirectory                  

                      );

    ds.ReadXml(filePath);

                      ds.Tables[0].PrimaryKey

                            = new DataColumn[]

    {ds.Tables[0].Columns[“Code”]};

                            DataRow dr=

                                ds.Tables[0].Rows.Find

                                (_view.SearchCriteria);

    if (dr != null)

                      {

                            _view.FirstName

                               = dr[“FirstName”].ToString();

                            _view.LastName

                               = dr[“LastName”].ToString();

                            _view.Address

                               = dr[“Address”].ToString();

                            _view.City

                               = dr[“City”].ToString();

                            _view.ErrorMessage

                               = “”;

    }

                      else

                      {

                            _view.FirstName = _view.LastName

                                = _view.Address = _view.City = “”;

                            _view.ErrorMessage

                                = “Contact not existing”;

    }

    }

    }

          else

          {

                _view.FirstName = _view.LastName =

                _view.Address = _view.City = “”;

                _view.ErrorMessage = “Not a valid code!!!”;

    }

    }

    Presenter would implement therefore a method named SetCustomerData which task is to find a customer of a given code and update the view with resulting data. In case the entered code is not a valid number presenter would show appropriate message on validator that there is a syntax error. In case there are no contacts with a given code presenter should empty view and show a message that not existing code has been entered.

    Illustration 9. Results of an example – Code 1 entered – user shown 

    Illustration 10. Results of an example – Non existing valid code entered

     

    Illustration 11. Results of an example – Invalid code entered

    Now I will show reuse of the presenter for implementing the same logic in totally different technology: WinForm

    I’ll slightly change the look by switching the places between search criteria and the error message and city would be presented now by ComboList

    Illustration 12. UI look of the view made by windows form

    Usage of MVP patterns allows me just to implement view interface to win form and to view up presenter by passing to its constructor WinForm and all the same functionality is present without touching a presenter. That’s why the presenter is speaking to interface which shouldn’t be technology specific

    Illustration 13. Wiring up the win form view to the presenter

    using System.Windows.Forms;

    using Presenter;

    namespace WinForm

    {

        public partial class UserViewForm : Form, IUserView

        {

            private UserViewPresenter _presenter;

            public UserViewForm()

            {

                InitializeComponent();

                _presenter = new UserViewPresenter(this);

                _presenter.SetCustomerData();

            }

          

            private void searchButton_Click(object sender, System.EventArgs e)

            {

                _presenter.SetCustomerData();

            }

            #region IUserView Implementation

                      // The same implementation like in WebForm case

                      // Wire up the control text properties to interface members

            #endregion

        }

    }

     

    So the complete solution would be something like:

    Illustration 13. Complete project tree

    And the result is the same functionality encapsulated in presenter is been reused for a win form

    Illustration 14. Results of an example in win form – Existing code entered

    Illustration 15. Results of an example in win form – Non existing code entered

    Illustration 16. Results of an example in win form – Invalid code entered

    Conclusion

    MVP is very powerful UI design pattern which has multiple benefits for developing all kinds of user interfaces. That is the reason why CAB (Composite Application Block) is using it as a one of basic UI building principles

    Abstract Factory Design Pattern Implementation in C#

     
    Abstract Factory Design Pattern Implementation in C#

    Context

    An abstract factory provides an interface for creating families of related objects without specifying their concrete classes.

    Sometimes one wants to construct an instance of one of a suite of classes, deciding between the classes at the time of instantiation. In order to avoid duplicating the decision making everywhere an instance is created, we need a mechanism for creating instances of related classes without necessarily knowing which will be instantiated.

    Solution

    Create an Abstract Factory class to answer instances of concrete classes (usually subclasses). The class of the resultant instance is unknown to the client of the Abstract Factory.

    There are two types of Abstract Factory:

    • Simple Abstract Factory is an abstract class defining Factory methods to answer instances of concrete subclasses. The choice of which subclass to instantiate is completely defined by which method is used, and is unknown to the client.
    • The second form of Abstract Factory is an abstract class defining a common protocol of Factory methods. Concrete subclasses of the abstract factory implement this protocol to answer instances of the appropriate suite of classes.

    See below for an example, both VB.NET and C# implementation

    Applicability

    • Need to abstract from details of implementation of products -The system shall be independent of how its constituent pieces are created, composed, and represented.
    • Need to have multiple families of products – The system shall be configured with one of multiple families of products.
    • Need to enforce families of products that must be used together – A family of related product objects is designed to be used together, and you need to enforce this constraint.
    • Need to hide product implementations and just present interfaces – You want to provide a class library of products, and you want to reveal just their interfaces, not their implementations.

    Characteristics

    • An abstract factory is an object maker.
    • It typically can produce more than one type of object.
    • Each object that it produces is known to the receiver of the created object only by that object’s interface, not by the object’s actual concrete implementation.
    • The different types of objects that the abstract factory can produce are related — they are from a common family
    • An abstract factory isolates concrete classes
    • It makes exchanging product families easy
    • It promotes consistency among products
    • It supports adding new kinds of products and their families.

    Example

    The Example here has an implementation of an Abstract Factory as an Interface IAVDevice that has methods that can create an Audio object and a Video object.

    The client Codes against IAVDevice and gets IAudio and IVideo interfaces.

    Passing “cd” in the command line creates a family of cd objects (Audio and Video) and “dvd” creates a family of dvd objects (Audio and Video).

    The client doesn’t care which object (cd audio video or dvd audio video), IAVDevice interface returns as it codes against IAudio and IVideo interface.

    C# Implementation

    To run the example from console first make the exe and then run it by using

    csc /out:AbstractFactory.exe AbstractFactory.cs  //Creates AbstractFactory
    AbstractFactory cd                               //CD Family
    AbstractFactory dvd                              //DVD Family

    using System;

    public interface IAVDevice
    {
        IAudio GetAudio();
        IVideo GetVideo();
    }

    public interface IVideo
    {
        string GetPictureQuality();
    }

    public interface IAudio
    {
        string GetSoundQuality();
    }

    class CCd:IAVDevice
    {
        public IAudio GetAudio()
        {
            return new CCdAudio();
        }
        public IVideo GetVideo()
        {
            return new CCdVideo();
        }
    }

    class CDvd:IAVDevice
    {
        public IAudio GetAudio()
        {
             return new CDvdAudio();
        }
        public IVideo GetVideo()
        {
            return new CDvdVideo();
        }
    }

    class CCdAudio:IAudio
    {
        public string GetSoundQuality()
        {
            return "CD Audio is better then DVD Audio";
        }
    }

    class CCdVideo:IVideo
    {
        public string GetPictureQuality()
        {
            return "CD video quality is not as good as DVD";
        }
    }

    class CDvdAudio:IAudio
    {
        public string GetSoundQuality()
        {
             return  "DVD Audio is not as good as CD Audio";
        }
    }

    class CDvdVideo:IVideo
    {
        public string GetPictureQuality()
        {
            return "DVD video quality is better then CD";
        }
    }

    class CAVMaker
    {
        public IAVDevice AVMake(string xWhat)
        {
            switch (xWhat.ToLower())
            {
                case "cd"":
                    return new CCd();
                case "dvd"":
                     return new CDvd();
                default:
                    return new CCd();            
            }
        }
    }

    public class AbstractFactory
    {
        static void Main(string[] args)
        {
            CAVMaker objFactMaker = new CAVMaker();
            IAVDevice objFact;
            IAudio objAudio;
            IVideo objVideo;
            string strWhat;
            strWhat = args[0];
            objFact = objFactMaker.AVMake(strWhat);
            objAudio = objFact.GetAudio();
            objVideo = objFact.GetVideo();
            Console.WriteLine(objAudio.GetSoundQuality());
            Console.WriteLine(objVideo.GetPictureQuality());
        }
    }

    MVC vs. MVP vs. MVVM


    MVC vs. MVP vs. MVVM

    An important FAQ. The answer actually depends on where the person is coming from. MVC is a fundamental pattern which has been tweaked quite a bit to fit into various platforms. For instance if you had asked anybody how to implement an MVC in ASP.NET (prior to release of ASP.NET MVC framework) you would get very different answers. So let’s start with basic. The common motivation behind all 3 is separation of concerns, cutting flab from UI (good for UI designers), swapping UIs (for instance windows to web), make UI easy for Unit Testing, etc. Have a look at the below diagram, I have taken it from CAB documentation.

    MVCMVP

    MVC: Three components – View (your UI), Model (your business entities / data – that view is displaying) & Controller (contains the logic that alters the model depending on the action triggered by UI, typically implementing a Use Case). It’s widely known that MVC is a compound pattern (View and Controller have Strategy implementation, View itself can be a Composite implementation & View and Model are synched through Observer). In this case Controller doesn’t know anything about View, and the idea is that a View can switch Controllers (for instance depending upon who has logged to the system) & a single controller can be used by multiple Views. View subscribes to the changes done to the model & hence both are sync from the data perspective. One of the disadvantages of MVC is that it’s difficult to unit test. Controller manipulates the data but how about asserting those changes from a view perspective. For instance on click of a button you raise an event to controller, and controller modifies the value in model. This value modification changes the font size / color in View. Unit testing this scenario is slightly difficult in MVC.

    MVP: Again three components. But dependencies change (look at arrows in the diagram). Over here we replace Controller with Presenter (one which presents the changes done in model back to view). The main difference between both is that Presenter refers back to the view while Controller doesn’t. Normal pattern found here is to create an abstraction of the View (in terms of properties / events) & Presenter refers to it. This makes the mocking of View much easier & hence the Unit Testing aspect. Presenter here hence takes the responsibility of not only manipulating model but also updating the view. Of course the implementations of MVP differ in real world in terms of how much thin the view is, some prefer keeping basic logic still inside view & taking complex logic in presenter, while others prefer keeping the entire logic in Presenter. Martin fowler describes 2 variations on MVP on these lines namely – Supervising Controller & Passive View described below

    (A Passive View handles this by reducing the behavior of the UI components to the absolute minimum by using a controller that not just handles responses to user events, but also does all the updating of the view. This allows testing to be focused on the controller with little risk of problems in the view.

    Supervising Controller uses a controller both to handle input response but also to manipulate the view to handle more complex view logic. It leaves simple view behavior to the declarative system, intervening only when effects are needed that are beyond what can be achieved declaratively.)

    MVVM: Model–View-ViewModel talks of creating a new model (in addition to your domain model). This model normally adds additonal properties from the prespective of View (as we understand that View has controls in addition to data which it’s displaying). For instance if View had a property IsChecked and Presenter was setting in classic MVP, in MVVM Presenter will have that IsChecked Property which View will sync up with (doesn’t it look like Strategy pattern has been replaced with Observer?). So now a Presenter becomes more like a combo of – View Properties & Model properties which would be synchronized with View. So why not rename Presenter to ViewModel? Do that and you get MVVM. MVVM is attractive for platforms which support bi-directional binding with less effort. Also a minor tradeoff is ViewModel unlike Presenter can stand on its own (Presenter normally requires a View’s interface). Martin fowler describes similar pattern called Presentation Model & Josh Smith captures MVVM implementation for WPF / Silverlight in this article.

    MVVM

    ASP.NET MVC: So what has MVC got to do with ASP.NET MVC? First, Web works on a different model. Here, user interacts with HTML in browser and send a request back to the server for processing (for client side Ajax you might go just for data). As the interaction is normally stateless, when the request comes back to the server we need to recreate our View, load the model back & manipulate both of them as required. There are 2 variations on how handle this recreation – Page Controller & Front Controller. Make Page the decision maker – in this widely implemented pattern HTTP request is specific to physical page on server (.aspx for instance) & page in turn creates itself (builds the view from postback data) decides what model it needs and triggers the manipulation (events in codebehind file) it requires. As you see here the distinction between View & Controller becomes blur & is little difficult to separate. This where ASP.NET MVC comes in which behaves like a Front Controller – where Controller is the decision maker. Here all HTTP requests are mapped to methods on the Controller Class. Controller class recreates the model & view as required and does the manipulations. This makes unit testing easier as we can directly instantiate the front controller class & invoke methods on it to perform the assertions.