locked
Why MVP/MVC? RRS feed

  • Question

  • Why Model-View-Controller/Model-View-Presenter? What problem does it solve? i've written quite a few large business applications, and seem to have had an easy time of it - all without MVP/MVC.

     

    Jean-Paul Boodhoo writes:

    Why is it bad to have lots of logic in the UI layer? The code in the UI layer of an application is very difficult to test without either running the application manually or maintaining ugly UI runner scripts that automate the execution of UI components. While this is a big problem in itself, an even bigger problem is the reams of code that are duplicated between common views in an application. It can often be hard to see good candidates for refactoring when the logic to perform a specific business function is copied among different pieces in the UI layer. The MVP design pattern makes it much easier to factor logic and code out of the UI layer for more streamlined, reusable code that's easier to test.

     

    So i see the problems:

    • difficult/impossible to write unit tests
    • duplicated code between common views

    i'll focus on the second point, duplicated code, since we don't do unit-testing of entire modules (at my own peril). What code is duplicated?

     

    Can someone give me an example where in a "traditional" Windows/database application code is duplicated, and how splitting it into 3 files makes it easier to maintain?

     

     

     

    The No.1 google result for "Why MVC" says:

    • Modular separation of function
    • Easier to maintain

    The first point is circular: MVC is modular separation of function (it's like saying that oranges taste orangey). The 2nd point, "easier to maintain", implies that the code i currently write is harder to maintain.

     

    Can someone give me an example where in a "traditional" Windows/database application code is harder to maintain, and how splitting it into 3 files makes it easier to maintain?

     

     

    Alternativly, can someone direct me to a resource that walks me through how what i do now is bad and how MVC is better.

    Thursday, October 11, 2007 3:27 PM

All replies

  •  

    You raise a lot of points and I'm not going to answer them all (I'm sure others will provide more on this one)

     

    #1: duplicated code between common views:

    The emphasis here is on common. If you need to do similar things in several different views you might end up with duplication of logic in those views. I think the main issue here is that many times you need the methods to be physically close to each other in order to spot duplications. Often there's only parts of a given method that are duplicate and should be refactored out to a common method or class. If you have all your logic in a single place it should be easier to spot duplications.

    If your code is highly modularized you might be in an OK position without MVP/MVC. But if you connect to the database and execute a common query in 20 different forms in your appliction and you need to change either the query or connection properties, it goes without saying that you would be better off having that in one place. Data validation code is another type of code that easily gets duplicated if you don't have it a central location.

     

    #2 Easier to maintain:

    The more cohesive the code the easier it is to maintain. If you have UI logic, UI control manipulation, database access and business logic all in a single place it would clearly be harder to maintain than if you had those separated in different classes. Separation of concerns is an important design principle. A class should only have one reason to change. If it doesn't it will be harder to maintain. Lets say you have business logic in the UI code. How would go about having one developer working on the business logic while another works on the UI? Sure, you could argue that that could be done with partial classes, but that could lead to other problems. Lets say you want to deploy an updated version of the business logic DLL. How could you if all the code is embedded in the form.

    I believe that if you have only one type of code in one place it is easier to maintain that code. If you have a class with database code intermingled with UI stuff and business logic, the code in the class will be much more crowded and hard to maintain.

     

    Another benefit with MVP is that it lets you swap out either the view or the presenter/controller without touching the other. You could have multiple views having one controller and one model or you could have one view that sometimes uses one controller sometimes another. etc.

     

    I would point you to two sources:

    The first is not related to MVP/MVC specifically, but it deals with many of the design principles behind it.

    Peter C. Martin has written a book: Agile Principles, Patterns and Practices in C#. The book is excellent.

    http://www.amazon.com/Principles-Patterns-Practices-Robert-Martin/dp/0131857258/ref=sr_1_1/103-0595961-7925411?ie=UTF8&s=books&qid=1192144313&sr=1-1

     

    The second would be to Jeremy Miller's MVP blog post series which is also excellent.

    http://codebetter.com/blogs/jeremy.miller/archive/2007/07/25/the-build-your-own-cab-series-table-of-contents.aspx

     

    I hope I answered some of your questions.

     

    Kim

    http://blogs.microsoft.co.il/blogs/kim

     

    Thursday, October 11, 2007 11:18 PM
  • Over the years, I have used the MVP/MVC pattern on several (Web and WinForm) projects. There are several good reasons for using these patterns and most projects would benefit from using these and other patterns.

    First, is helps to clarify that Model View Presenter (MVP) and Model View Controller (MVC) are two entirely different patterns that solve the same problem .Both patterns have been in use for several years and focus on separating the view (UI) from the model (Business Classes).

    Using the MVC pattern developers create controller classes that are responsible for responding to UI events and updating the model according to the action (event) invoked. While using the MVP pattern developers create presenter classes that do basically the same thing; but, also include the use of a .Net interface to talk to the view. The use of this interface is the major differences between the patterns and makes the presenter generally more loosely coupled then a controller. In some advanced scenarios you need to have both presenters and controller. In those cases the classes work together to isolate the view from the model.

    Benefits of using either pattern

    ·         Loose coupling – The presenter/controller are an intermediary between the UI code and the model

    ·         Clear separation of concerns/responsibility

    o    UI (Form or Page) – Responsible for rending UI elements

    o    Presenter/controller – Responsible for reacting to UI events and interacting with the model

    o    Model – Responsible for business behaviors and state management

    ·         Test Driven – By isolating each major component (UI, Presenter/controller, and model) it is easier to write unit tests. This is especially true when using the MVP pattern which only interacts with the view using an interface.

    ·         Code Reuse – By using a separation of concerns/responsible design approach you will increase code reuse. This is especially true when using a full blown domain model and keeping all the business/state management logic where it belongs.

    ·         Hide Data Access – Using these patterns forces you to put the data access code where it belongs in a data access layer. There a number of other patterns that typical works with the MVP/MVC pattern for data access. Two of the most common ones are repository and unit of work. (See Martin Fowler – Patterns of Enterprise Application Architecture for more details)

    ·         Adaptable to change – I have been in this business for over 12 years and two things have changed more than any other (UI and Data Access). For example in .Net today we have several UI (WinForm, ASP.Net, AJAX, SilverLight, and WPF), and data access (DataSets, DataReaders, XML, LINQ, and Entity Framework) technologies. By using MVP or MVC it is easier to plug in any of these UI or data access technologies and even possible to support more than one at a time.

    To recap the MVP and MVC are two separate patterns that address the same problem. Both patterns focus on isolating the UI from the model and these patterns are more adaptable to change then traditional approaches. I hope you found this helpful.

    Monday, October 15, 2007 4:18 PM
  • I'll give you some examples from my previous and current projects:

     

    We have a pretty big 3 tier application built in .NET, using Win Forms for UI and web services.

     

    We plan to move the UI to WPF and replace web services with WCF.

     

    We created an abstraction layer that separates all of them and makes the transition to the new technologies easier.

     

    If you are interested to read more I recommend the Software Abstraction Layer article. It also has a proof of concept prototype:

    http://danutp.blogspot.com/2007/10/abstraction-layer.html

     

    Also, have you looked at Acropolis?

    http://windowsclient.net/acropolis/

     

     

    Danut

     

    Monday, October 15, 2007 5:19 PM
  • Let's start with a real world example.

     

    There are two text boxes, both for entering a dollar amount. The first is optional, the second is mandatory:

     

    Extra Charges: [         43,223.02 ]    <---Optional

    Total Philbons: [       134,997.98 ]     <---Mandatory

     

    So the business rules are that Extra Charges is optional dollar amount, and Total Philbons is mandatory.

    The user interface rule is that if a field is mandatory: color is red. If a field is optional: color it blue. If an invalid value is entered in either: color it red. Finally, if a value is entered, put it to the default (window) color. Or the flowchart:

     

    Code Block
    --Yes--> --Yes--> [Color Blue]
           |                         |
           No                        No
           |                         |
     dollar amount?> ---No----> [Color Red]
           |
           |
     [Color Window]

     

     

    Now in the "old" way, i would have an "Change" event handler on each Text box. e.g

     

    pseudocode

    ExtraChargesTextBox_OnChange()

    {

        if IsStrMoney(ExtraChargesTextBox.Text, ALLOW_BLANKS)

           ExtraChargesTextBox.Color = clWindow

        else

           ExtraChargesTextBox.Color = clPaleRed;

    }

    TotalPhilbonsTextBox_OnChange()

    {

        if IsStrMoney(TotalPhilbonsTextBox.Text, DONT_ALLOW_BLANKS)

           TotalPhilbonsTextBox.Color = clWindow

        else

           TotalPhilbonsTextBox.Color = clPaleRed;

    }

     

     

    But this code is "bad", because i've put the business rules (of what is optional, and what consitutes a valid value) into the presentation code.

     

    The "better" way is to have a 2nd class, termed a Controller, that decides if a field is optional or mandatory, what a valid, invalid, and unentered values are. From there the UI decides how to present the business rules and information. So:

     

    Code Block

    pseudocode

    ExtraChargesTextBox_OnChange()

    {

        if Controller.IsExtraChargesStringValueValid(ExtraChargesTextBox.Text)

           ExtraChargesTextBox.Color = clWindow

        else

           ExtraChargesTextBox.Color = clPaleRed;

    }

    TotalPhilbonsTextBox_OnChange()

    {

        if Controller.IsTotalPhilbonsStringValueValid(TotalPhilbonsTextBox.Text)

           TotalPhilbonsTextBox.Color = clWindow

        else

           TotalPhilbonsTextBox.Color = clPaleRed;

    }

     

    class Controller

       method IsExtraChargesStringValueValid(string S)

       {

          return IsStrMoney(S, ALLOW_BLANKS);

       }

       method IsTotalPhilbonsStringValueValid(string S)

       {

          return IsStrMoney(S, DONT_ALLOW_BLANKS);

       }

     

     

    So now this is a good thing(?). In one file we have our "presentation", and in a separate file we have our "business rules". And if the business rules change, then nothing has to change with the presentation code. It's clean, modular, and is easier to maintain.

     

     

    Except it's not any of those things. If i want to add a new field to the form, i have to add it in two files, rather than one, i have to keep two files synchronized. Even worse, we i was masochistic enough to define an interface for my controller (to further enfore the separate of UI and business logic paradigm), now i have to update 3 files in order to add one change.

     

    And with the code separated into different areas, it's harder to see what goes on. If i want to find out why a field is blue rather than red, i have to jump through 2 source files. And again, if i used an controller interface, i can't trace the code at design time at all, i have to run it in order to find the implementation class that is doing the work.

     

    Plus we have the myth that one developer does the UI, while another does the controller. That way they can focus on their own areas of expertise. The graphics guy doesn't have to understand too much code, and the controller coding guru doesn't have to worry about rgb color values.

     

    Except it's always one guy doing one feature. i add my stuff to the controller for my feature, and another guy adds stuff to the controller for his feature. We both work on our own screens, we both have to fight over the interface and the controller code files. It's triple the files so triple the work, harder to follow at design time and run time. But at least we gain the abstract advantage that it's better because it's separate.

     

    You may say,

    But Ian, if the customer decides that Extra Charges are now mandatory, you only need to change it in the one place:

    Code Block

    method IsExtraChargesStringValueValid(string S)

       {

          return IsStrMoney(S, DONT_ALLOW_BLANKS);

       }

     

     

    It's a business rule, and so you only had to change it in the one spot.

     

    The same is equally true of the original code:

    Code Block

    ExtraChargesTextBox_OnChange()
    {

        if IsStrMoney(ExtraChargesTextBox.Text, DONT_ALLOW_BLANKS)

           ExtraChargesTextBox.Color = clWindow

        else

           ExtraChargesTextBox.Color = clPaleRed;

    }

     

     

    Except the non-MVC approach is easier since i'm coming to a project and am told, "Hey Ian, can you change it on the pumpernickle screen so that they have to enter extra charges?"  And so i go to the pumpernickle screen, go to the Change event handler of ExtraChargesTextBox and see the code that it's doing, and how to change it. With MVC i have to direct to another file, and then possibly to another file (trying to figure out which class implements the interface IController, because there's no code in the interface, just abstract methods.

     

    Now for maintainance examples. When the user tries to save, i want the UI to show the user has entered invalid values - i want to put a balloon-hint pointing at the bad thing, saying why it's bad. e.g.

    Enter Total Philbons

    You must enter the total philbons.

    or

    Enter Total Philbons

    Total Philbons cannot be negative.

    or

    Enter Total Philbons

    "347,889,.8" is not a valid amount.

     

    So now we have to go back and update the IController interface and add an interface:

     

    Code Block

    pseudocode

    method IsTotalPhilbonsStringValueValid(string S, out InvalidReason badReason)

    {

       if S = ""

       {

          badReason = InvalidReason.ItsEmpty;

          return False;

       }

       else if  IsStrMoney(S, DONT_ALLOW_BLANKS)

       {

          badReason = InvalidReason.NotAMoneyValue;

          return False;

       }

       else

          return True;

       }

    }

     

    So if the UI guy want to change presentation, we have to update 3 files, as well as crossing layers. i could just save myself 3 steps, making it easier to read, follow, understand, and update, by having stuff in one spot.

     

    Kim Major says:

    The more cohesive the code the easier it is to maintain. If you have UI logic, UI control manipulation, database access and business logic all in a single place it would clearly be harder to maintain than if you had those separated in different classes.

     

    Then i must need to have it explained to me clearly why it's harder to maintain code that's together, rather than scattered around. It certainly isn't easier to maintain when i have to maintain it.

     

    Feel free to respond with real world examples where MVC/MVP is easier.

    Wednesday, October 17, 2007 6:08 PM
  • I'll try to keep this short.

    On your point, one dev does both presenter and UI. I agree. This might not always be true, but lets assume it is the normal case.

     

    You wrote:

     

    Code Block

    ExtraChargesTextBox_OnChange()

    {

        if Controller.IsExtraChargesStringValueValid(ExtraChargesTextBox.Text)

           ExtraChargesTextBox.Color = clWindow

        else

           ExtraChargesTextBox.Color = clPaleRed;

    }

     

     

    I would claim that you didn't move the UI logic entirely to the presenter. Instead I would do something like:

    Pseudo code:

     

    UI:

    Formxxx_Load(...)

    {

    _presenter.OnViewReady();

    }

     

    Presenter:

    OnViewReady()

    {

    _view.SetXXXRequired(); // Let the view decide on the color

    _view.SetXYZRequired();

    }

     

    UI:

    RequiredColor = clPaleRed;

     

    SetXXXRequired()

    {

    ExtraChargesTextBox.Color = RequiredColor

    }

     

    SetXYZRequired()

    {

    ExtraChargesTextBox.Color = RequiredColor

    }

     

     

    At this point we have the view set up. And the user can start to enter data:

    ExtraChargesTextBox_OnChange()

    {

    _presenter.OnExtraChargesChanged();

    }

     

    Presenter:

    OnExtraChargesChanged()

    {

    // This is the UI logic!

    string charge = _view.ExtraCharge;

    // The presenter does not handle business logic!

    if (_chargeService.IsExtraChargeValid(charge))

    {

    _view.SetXXXValid();

    {

    _view.SetXXXRequired();

     

    // If you need an error message the presenter decides when to show it.

    _view.ShowXXXValidationError(errorMessageFromValidation);

    }

    }

     

    Bare with me, it has been a long day...

    MVP certainly has some overhead, but in complex UI scenarios it by far outweighs the maintenance cost over having everything burried in one file. More than anything I believe that it takes some time to get used to.

    If you do Unit testing then this discussion is moot, the benefit is obvious.

     

    Regarding your comment:

    Kim Major says:

    The more cohesive the code the easier it is to maintain. If you have UI logic, UI control manipulation, database access and business logic all in a single place it would clearly be harder to maintain than if you had those separated in different classes.

     

    Then i must need to have it explained to me clearly why it's harder to maintain code that's together, rather than scattered around. It certainly isn't easier to maintain when i have to maintain it.

     

    I'm not going to enter the argument why cohesive code is good. Steve McConnel does a much better job than me.

    Ok, maybe just a little. I might not be reading the English word "scattered" correctly, but to me it sounded like you mean the code is separated into different places for no good reason. That's not the case. The code is cleanly separated to each class with its own responsibility. The presenter does UI logic, the UI does rendering, and the business objects does business operations.

     

     

    I didn't manage to keep it short and I'm not sure I made any new arguments. But I hope you got something out of this.
    Wednesday, October 17, 2007 8:31 PM
  • The principles of cohesion and decoupling should lead to a design in which the things that change together remain together (in the same class). If while using MVC a trivial task such as adding a field to a business entity (and having it be available for editing in the UI) requires changes to be made in more than a single class, then MVC achieves neither cohesion nor any real abstraction and decoupling of business logic and UI logic. Having a concrete View bound to a concrete Model and using a concrete Controller provides absolutely no abstraction.

    Jack has a good point here.


    Wednesday, October 17, 2007 9:08 PM
  • I'm not going to enter the argument why cohesive code is good. Steve McConnel does a much better job than me.

     

    i'm speechless. i find it very odd that anyone would willingly structure code this way, even more so with the structure you presented.

     

    Perhaps i need this Steve McConnel to convince me.

     

    I might not be reading the English word "scattered" correctly, but to me it sounded like you mean the code is separated into different places for no good reason. That's not the case. The code is cleanly separated to each class with its own responsibility. The presenter does UI logic, the UI does rendering, and the business objects does business operations.

     

    Is there a "good reason" to separate things cleanly into their own class with their own responsibility? All i can see so far is that is makes code much harder to follow, write, understand and debug.

     

    i really can't belive that people would willingly write the code you posted.

     

     

    Wednesday, October 17, 2007 9:13 PM
  • I did a video on Model View Presenter about a month ago. It's a demo of using CodeRush and the pace is by much too fast to learn MVP from it, but at least you can see a working example.

     

    http://blogs.microsoft.co.il/blogs/kim/archive/2007/09/27/the-coderush-ivbug-presentation-amp-model-view-presenter-video.aspx

     

    BTW, did you read Jeremy Miller's series on MVP? He does a much better job than me on explaining this topic.

    http://codebetter.com/blogs/jeremy.miller/archive/2007/07/25/the-build-your-own-cab-series-table-of-contents.aspx

     

    Kim
    Wednesday, October 17, 2007 10:24 PM
  •  

    Why, in the world, would you do that to yourself? i'm sorry, i just don't see the value, only a cost - a huge cost.

     

     Kim Major wrote:

    BTW, did you read Jeremy Miller's series on MVP? He does a much better job than me on explaining this topic.

    http://codebetter.com/blogs/jeremy.miller/archive/2007/07/25/the-build-your-own-cab-series-table-of-contents.aspx

     

    He doesn't really explain anything, just talks about what he's done.

     

     

    How about another example. How would you rewrite:

     

    CheckBox1_Checked()

    {

    ListView1.Enabled = CheckBox1.Checked;

    }

     

    But more importantly, why did you structure it that way - and what do i gain by having it that way. i mean, i could follow the examples, that spread code randomly over files - but i'm not getting any value. And if i were to try to justify it to someone, the only thing i can say is:

     

    It's better this way. Everything is separated into its own functional blocks. The clean separation allows for easier maintainance and readability.

     

    i'd be lying through my teeth, because the separation does not allow for easier maintainance or readability. Looking at your code rework of mine - i could keep it, but the first thing i would do it refactor it down to what i had.  What am i losing by having it my way?

    Thursday, October 18, 2007 5:09 PM
  • All i see when people present MVC/MVP is:

     

    Form1.CheckBox1_Checked()

    {

       presenter.DoSomething();

    }

     

    Presenter.DoSomething()

    {

       view.NotYet();

    }

     

    Form1.NotYet()

    {

       presenter.Almost();

    }

     

    Presenter.Almost()

    {

        view.KeepGoing();

    }

     

    Form1.KeepGoing()

    {

    presenter.NotQuoteYet();

    }

     

    Presenter.NotQuiteYet()

    {

       view.YeahILied();

    }

     

    Form1.YeahILied()

    {

       presenter.ReallySoonNow();

    }

     

    presenter.ReallySoonNow()

    {

       view.DooEet();

    }

     

    Form1.DooEet()

    {

       ListView1.Enabled = CheckBox1.Checked;

    }

     

     

    And it's so simple.

    Thursday, October 18, 2007 5:22 PM
  • Some interesting comments, but I think we are starting to get off track. When you decided to use any pattern (Especially the more complex ones MVC/MVP, Domain Model, Repository, etc…) there are always pros and cons. What a good developer/architect needs to do is pick and choice the right set of patterns to address their problem space. This is one of the reasons why I like TDD, because it helps guide you through this process of choosing the right approach.

    Here are the guidelines I recommended following when using design patterns:

    • Follow proven OOD design principles (Open/Close, Single Responsibility, Interface Segregation, etc…)
    • Remember patterns are concepts and not out of the box solutions. Depending on your problem space the implementation might be different.
    • Study how existing frameworks use patterns (e.g.  ASP.Net and EntLib both utilize the provider model)
    • If possible use an existing framework over building your own.
    • Re-factoring and TDD good hand and hand with using design patterns
    • At first using design patterns and TDD might seem like extra work, but in reality they will save you time in the long run.  How many of us have stayed up late fixing bugs the day before release.

    Hopefully this helps clarify a few things. Just remember using design patterns and TDD is not a silver bullet (There are no silver bullets).  They are just tools to help build better software. If you like more information check out o my blog post on the differences between MVC/MVP and I highly recommend the Agile Principles, Patterns, and Practices in C# book.

    Thursday, October 18, 2007 9:40 PM
  • When you decided to use any pattern

     

    Problem is: it wasn't my decision. We were hired by a company to help their developer finish a project that is 8 months behind schedule. He decided to structure it this way "because that's the way Microsoft recommends it be done" (referring to P&P, CAB, SmartClient, ...)  If it were me i would not structure this project using MVC/MVP randomness, and be done in a half the time.  But we have to mirror what he has, and look bad when it takes us twice as long to complete the project.

     

    Now, i can split up code into as many files as MVP wants, as frustrating, painful, and difficult as that is. i can do it, but it's not helping. i'm sure there is a reason why people do it. And i'm sure that once i understand the logic of it, i'll understand the need for the extra headaches - but nobody can tell me why.

     

     

    What i'd really love is an "Essential MVP", like Don Box's "Essential COM". The book doesn't explain how to develop COM objects, the book explains why COM. He starts from the way things are (straight C++ classes in a dll), walks into the problems that creates, and piece by piece creates workarounds for those problems, finally presenting a generalized solution. By the end of chapter one he's walked you through the discovery of COM. The remaining chapters detail how Microsoft chose to implement it's COM discovery - and every API call is obvious and intuitiave.

     

     

    i've tried to trick people into doing the same thing here. i'll start with a real world example

     

    Code Block

    CheckBox1_OnClick()

    {

       ListView1.Enabled = CheckBox1.Checked;

    }

     

     

    And now is where forum members jump in, and give a detailed description of how you this code causes me problems,  walk through why it's a problem, propose possible half-solutions, give an actual solution for this particular case, and then generalize the solution to handle other similar code, finally ending up with "discovering" Model-View-Presenter. Saying MVP is better because "everything is separated, giving easier readability and maintainability" is as valid as me saying non-MVP is better "because everything is together, giving easier readability and maintainability."

     

    The people who wrote Patterns and Practices, and those who are writing Acropolis all know the why, they assume i know the why, and they are just creating their particular implementation of MVP framework.

     

    So, is there perhaps a book on Model-View-Controller/Model-View-Presenter? Not how to structure to code as MVP/MVC, but why? If i understand the why, then the how becomes obvious. In fact, not even why MVP, but why separation? And then the book can explain MVP as a particular implementation of the separation.

     

     

     

    Friday, October 19, 2007 1:26 PM
  • You’re correct understanding why to use a pattern is as important as knowing how to use them. I would suggest picking up some good books on OOD and design patterns (See my recommend list below) to get a better understanding of the concepts. But, unfortunately you are not going to get the knowledge of why until you use patterns and TDD on a daily bases. 

     

    Applying UML and Patterns

    Patterns of Enterprise Application Architecture

    Refactoring to Patterns

     

     

     

    Friday, October 19, 2007 2:27 PM
  • But, unfortunately you are not going to get the knowledge of why until you use patterns and TDD on a daily bases. 

     

    i assume that the person who invented MVC wasn't using MVC on a daily basis before he invented it - it wasn't invented yet.

     

    And in 10 years of custom software development i've not come across some intractable problem that requires some (as yet unknown to me) solution.

     

    But i will uTorrent the aforementioned books, and give them a good going over.

    Friday, October 19, 2007 8:38 PM
  • While MVC/MVP may not be the right approach, seperating UI related code from other application specific (business logic) code improves your design in terms of code reuse and flexibility. Much of your application's UI appearance and behavior remains similar while the user experiences different use cases - those cross-application behaviors should be defined once so that they can be easily maintainable and reusable. You will have a hard time achieving that kind of flexibility if your business logic is written in terms of Click handlers, not to mention the flexibility required for the important ability of switching to a completely different UI framework without impacting business logic code.
    Sunday, October 21, 2007 11:44 PM
  • Feel free to give an example.

    Monday, October 22, 2007 2:19 PM
  • Gladly. This sample is over-simplified and useless but can hopefully show what I mean.

    interface MyFormBuilder
    {
    void BuildGridSection(Action<string> addColumn);
    void BuildNonGridSection(Action<string> addLabelAndTextBox);
    }

    class MyForm : System.Windows.Forms.Form
    {
    System.Windows.Forms.DataGridView _gridView;
    System.Windows.Forms.Panel _nonGridSection;

    public MyForm(MyFormBuilder builder)
    {
    InitializeComponent();

    builder.BuildGridSection(
    delegate(string columnName)
    {
    // add a column titled 'columnName' to the _gridView...
    });
    builder.BuildNonGridSection(
    delegate(string caption)
    {
    // add a label and textbox to the _nonGridSection accordingly...
    });
    }
    }

    MyForm represents the UI layer and is decoupled from the specific application logic by the MyFormBuilder interface. The interface can now be implemented in a number of different scenarios to achieve reuse of the UI layer. The UI layer can also be easily replaced because it consists of a single class instead of many classes for each of the scenarios.

    A well designed UI layer should, of couse, be a lot more comprehensive, to a point where adding a standard use case may be done without any concrete UI code (Forms, Controls, etc...).
    Monday, October 22, 2007 10:22 PM
  • I just came across this article. It lays out the background and evolution of the MVP/MVC pattern.

    http://ctrl-shift-b.blogspot.com/2007/08/interactive-application-architecture.html

     

    Wednesday, October 24, 2007 4:26 PM
  •  Kim Major wrote:

    I just came across this article. It lays out the background and evolution of the MVP/MVC pattern.

    http://ctrl-shift-b.blogspot.com/2007/08/interactive-application-architecture.html

     

    Thank you. The books that Todd mentioned weren't much help.

     

    i've giving it a read. It's quite prolix; someone needs to pull the stick out.

    Thursday, October 25, 2007 5:37 PM
  •  Yoni Rapoport wrote:
    Gladly. This sample is over-simplified and useless but can hopefully show what I mean.

    interface MyFormBuilder
    {
    void BuildGridSection(Action<string> addColumn);
    void BuildNonGridSection(Action<string> addLabelAndTextBox);
    }

    class MyForm : System.Windows.Forms.Form
    {
    System.Windows.Forms.DataGridView _gridView;
    System.Windows.Forms.Panel _nonGridSection;

    public MyForm(MyFormBuilder builder)
    {
    InitializeComponent();

    builder.BuildGridSection(
    delegate(string columnName)
    {
    // add a column titled 'columnName' to the _gridView...
    });
    builder.BuildNonGridSection(
    delegate(string caption)
    {
    // add a label and textbox to the _nonGridSection accordingly...
    });
    }

    }

     

    If i'm not reading it wrong: you left out the class that implements MyFormBuilder.

    Friday, October 26, 2007 2:43 PM
  • Why not MVP?

     

    Because i've spent 2 hours looking for the code that runs when the text in an edit box is changed.

     

    Do you have any idea how maddening that is? Two hours to find the "On Text Box Change" code.

     

    i've still not found it. But not to worry, because there is a clear separation of the domains of control of the various parts of system; making the system easier to debug and maintain.

     

    i'll get to the debugging and maintaining right after i find the code i need to debug and maintain.

     

     

    Edit: i've given up trying to follow the automagically created objects and interfaces that do stuff in isolated files without anyone asking. i've taken to opening random files, trying to guess what they do, and divine if they might be involved in the MVP process of the edit box i'm after.

     

     

    Edit: Perhaps i'm thinking of this in the wrong way. i was told to fix the code that runs when they type in this text box. That's sooo non-MVP thinking.

     

     

    20071031

    Edit: i finally found the code. i remember the original developer saying he used a regular expression somewhere. i searched the solution and found 7 references to the .NET regular expression engine. After an hour i managed to determine which one was near the code i was looking for.

    Friday, October 26, 2007 2:47 PM
  • Hey Jack.. I agree with you. I don't think most of the time, people over-use the MVC/MVP pattern just because it's a design pattern. People keep telling me that it's more flexible and can be extended in the future... to me, it's like tell me to build a car with 3 engine slots just in case people want to add more engines to the car...

    A lot of people also argue that when the complexity increase, it is better to separate the layers to simplify the code.... it's true theoretically, but most of the time, when a view gets too complicated, the presenter will most likely be very messy as well..

    that being said, i do find some benefits..
    1.) TDD - if you want to test the business logic, it is easier to have MVP pattern and mock the view so that you can call the presenter function easily (although i was able to create GUI and raise the specific GUI event to test some business functions..)
    2.) Multiple views that uses the same presenter. Form example..

    Interface IView
    {
    List<string> ErrorMessages ();
    void DisplayError();
    }

    Class View1 : IView
    {
    public void DisplayError()
    {
    // implementation here
    }
    }

    Class View2 : IView
    {
    public void DisplayError()
    {
    // implementation here
    }
    }

    //presenter
    Class Presenter
    {
    private void OnSubmit (object sender, EventArg args)
    {
    list<string> errorMsgs = BO.Validate();
    if (errorMsgs != null && errorMsgs.Count == 0)
    {
    doSomething();
    }
    else
    {
    IView.ErrorMessages = errorMsgs;
    DisplayError();
    }
    }
    }



    Wednesday, October 31, 2007 12:31 AM
  • It seems that MVC/P is only useful when you have dozens of developers - and each developer does his own part on his own screen. i don't know why i say that, but it just seems that way.  It's certainly not for the single developer, who has to write their code in 4x the files.

     

    It's also only useful if you do unit testing.

     

    And it could be useful if you mangle multiple "views" so they can work with a single "presenter".

     

     

    In our case, none of these apply.

    Wednesday, October 31, 2007 6:06 PM
  • Jack,

     

    I have to disagree. Using MVC/MVP is not about how many developers or how many views share a presenter. It is a about separating the responsibility of a use case across multi classes. Using TDD and writing unit tests helps you achieve this approach; but forcing you to think in OOD terms.

     

    In the end the goal you are trying to achieve is to put the most responsibility in the model (This is usually implemented as a domain model) and the least responsibility in the view. In most cases the presenter will have only the necessary code to bind the model to the view and to respond to events fired from the view. Using the MVC pattern things are a little different. The controller responds to events fired and the view is more responsible for binding the model.

     

    The MVP pattern support unit testing more by requiring the view to implement an interface. All communication between the view and the presenter is done using this interface and in most cases the view will not have any idea about the structure of the model. This is a good think and allows the view and the model to evolve independently of each other.

     

    If you have not heard yet Microsoft will be releasing an ASP.Net MVC framework soon http://weblogs.asp.net/scottgu/archive/2007/10/14/asp-net-mvc-framework.aspx. I would suggest you download the CTP when it gets releases to learn more about these patterns and TDD.

     

     

    Thursday, November 1, 2007 3:22 PM
  • MVP/MVC is just a design pattern. It is something that may help your design in certain scenario but not always.

    I don't know about you guy but I have seen a lot of people abuse the MVP pattern. Haven't you seen code where the IView and Presenter class just calling each other just for one user action?  Sometimes, I think it's better to code everything in the View and refractor it to a controller if it is needed but there is never time for refractoring. I think depending on the size of the application, the MVP/MVC pattern could be helpful. But if someone uses the MVP/MVC pattern without understanding how to delegate responsibility between view and controller/presenter, the code can get really messy...


    Friday, November 2, 2007 10:17 PM
  •  Todd F. Snyder wrote:

    It is a about separating the responsibility of a use case across multi classes.   In the end the goal you are trying to achieve is to put the most responsibility in the model and the least responsibility in the view.

     

    And i keep coming back to trying to find the value in this design pattern.

     

    i like the line from the G4 book Design Patterns: Elements of Reusable Object-Oriented Software:

     

    No discussion of how to use design patterns would be complete without a few words on how not to use them. Design patterns should not be applied indiscriminately. Often they achieve flexibility and variability by introducing additional levels of indirection, and that can complicate a design and/or cost you some performance. A design pattern should only be applied when the flexibility it affords is actually needed.

     

    And that's what i'm looking for - what is it that i'm missing in my simplistic Model-View/Control/Presenter design pattern that is solved by Model-View-Presenter or Modem-View-Controller?

     

    This is a good thing and allows the view and the model to evolve independently of each other.

     

    i think that's the faulty assumption: view and model don't evolve independantly of each other - at least not during the design, implementation, or support phases of a project.

     

    If i want the view to behave differently it will require changes in the presenter. If the model changes, it will requires changes to the view (and consequently the prestenter). If a business rule changes, then it will at least require changes to the view and probably the model.

    Thursday, November 8, 2007 6:41 PM
  • Jack,

    I believe the right question to ask is not "Why MVP/MVC?" but "Why use MVP/MVC in xxxx case?". As with any other design pattern, the project architect must carefully ponder the costs vs. the benefits of any given pattern.

    Although you have not given much detail about the project you are working on, it appears that the architect made a poor choice when he selected MVC just because "Microsoft says so". It does not help when a project is not properly documented (as it seems when you spend two hours looking at the code).

    Don't hate MVC because someone made the wrong choice!




    Thursday, November 8, 2007 11:32 PM
  •  eperales wrote:
    I believe the right question to ask is not "Why MVP/MVC?" but "Why use MVP/MVC in xxxx case?". As with any other design pattern, the project architect must carefully ponder the costs vs. the benefits of any given pattern.


    The Cost/Benefit analysis is where MVC/P get's into trouble. The only time i can see benefits is if we did have dozens of developers and we did unit testing. Take away either, or both, of those things and the number of benefits goes to zero.

     

    Two hours hunting through code? i wish it were that low. We're 4 months into this, and i've added one tiny setup module, and i've written about 20 lines of code for another module.  It's making me look stupid to my company, and our company look stupid to the customer.

     

    Don't hate MVC because someone made the wrong choice!

     

    Too late. Is it ever a right choice for the real world?

     

    i keep going back to give me an example. Give me an example of a problem with the simple way that using MVC solves. So far the best argument in favor of MVC is you won't see any benefits until you've been using it for a while.  i've been using (well...looking at) it for a while...

    Friday, November 9, 2007 3:11 PM
  • Let me give one teensy-weenie example among hundreds of the of frustrating minutia you have to suffer through when using MVCP design patterns.

     

    There's a Windows Workflow Foundation activity that calls back code. i want to see that code - so i can see what it does.  The event, unlike what you would think, it not raised through an event (where i could double-click to see the code). Instead there is an property where you specify an interface and a method on that interface

     

    Interface: IWS.FoamDisposition.Interface.Services.IDispositionLocalService

    Method: ShowStep

     

    So now i have to find the ShowStep method of IDispositionLocalService. i have no idea where IDispositionLocalService is, so i search for it. In the twenty matching results, i see no objects that implement IDisposisitionLocalService. But i do see another interface that descends from IDispostionLocalService:  IUserSessionTracker.

     

    i'm now in the file that defines IUserSessionTracker, but i need the object that implements IUserSessionTracker. So i search for IUserSessionTracker. In the 15 results, i didn't see any object that implements IUserSessionTracker. But i did notice that in a file called ModuleController there is a line:

    Code Block
    this
    .WorkItem.Services.AddNew<UserSessionTracker, IUserSessionTracker>();

     

     

    Which i assume means that the class UserSessionTracker implements IUserSessionTracker. So i follow UserSessionTracker to it's definition, and i begin scrolling for the method that i wanted to find in the first place, which was called....i can't remember.

     

    So then, to refresh my memory, i go try to find the workflow module again, and double click on the thing, then click on the thing, and find the method name again "ShowStep". And now all i have to do is go back to the module that that the object that i was looking at was in. That file was called....i can't remember.

     

    So then i want to kill myself by hitting myself over the head with a wine bottle.

     

    And i make this post.

     

    And this is where i ask myself, "Why can't i have this stuff in one file"

     

     

    Example 2 - 2:05pm

     

    Try to find the code that runs for each of these things:

    Code Block

    case DispositionStepsEnum.Carousel:

    _WorkItem.Commands[CommandNames.CarouselEntrypPrompt].Execute();

    break;

    case DispositionStepsEnum.CavityEntry:

    _WorkItem.Commands[CommandNames.CavityEntryPrompt].Execute();

    break;

    case DispositionStepsEnum.Defect:

    _WorkItem.Commands[CommandNames.DefectInputPrompt].Execute();

    break;

    case DispositionStepsEnum.DefectLocation:

    _WorkItem.Commands[CommandNames.DefectLocationInputPrompt].Execute();

    break;

    case DispositionStepsEnum.DefectResponsibility:

    _WorkItem.Commands[CommandNames.ResponsibilityInputPrompt].Execute();

    break;

    case DispositionStepsEnum.ProductionDateEntry:

    _WorkItem.Commands[CommandNames.ProductionDatePrompt].Execute();

    break;

    case DispositionStepsEnum.ProductionShiftEntry:

    _WorkItem.Commands[CommandNames.ProductionShiftPrompt].Execute();

    break;

     

     

     

    Can't follow anything at design time, and you step into Enterprise Library at runtime.

    Friday, November 9, 2007 5:06 PM
  • Interestingly enough I am starting a consulting project soon to move a system forward that was built with these patterns. The client has hired me to come up with a strategy to make the code more easily maintainable by your average programmer. It seems that these patterns are being abused in systems that didn't need the extra complication.

    I think the main issue is not the patterns, but the fact that the development tools just haven't caught up with the extra levels of abstraction, making it more difficult for developers to do their jobs in most cases, rather than easier. In Visual Studio there is no easy way to trace through the code. You really have to hold the whole application in your head to make anything happen.
    Saturday, November 10, 2007 1:26 AM
  • Jack,

    Ok, based on the last post (with the CAB code) I see where you're coming from and can feel your pain.

    I have been working on CAB (SCSF actually) projects and what you describe is IMHO a tooling problem and not a problem with MVP per-se. As ittybitty (???) stated in the previous post "...development tools just haven't caught up...".

    There are supplemental tools available that will make this code hunting a breeze. Both R# (www.jetbrains.com) and CodeRush (www.devexpress.com) will let you navigate through the code with much less friction.

    In the case of the sample you posted:

    Code Block
    case DispositionStepsEnum.Carousel:
    _WorkItem.Commands[CommandNames.CarouselEntrypPrompt].Execute();
    break;

     

     

    I use CodeRush and simply positioning on CarouselEntrypPrompt and pressing Shift+F12 will take you there. I know R# has similar functionality.

     

    A lot has been said about MVP in this thread and you are right in that the decision to use a design pattern needs to be evaluated in each case. In the case of MVP however I don't feel that there is much complexity added if you have the right tools. On the contrary, if you use MVP then you gain managability. You always know where the UI code is, you always now where the UI logic is and you always know where the business logic is. Everyone on the team have to be comfortable with the pattern, but once that is out of the way (and you have the right tools) you gain added consistency in your code base. That's at least how I see it.

     

    P.S If the people before you on that CAB project didn't make an effort to keep things managable you may be in for a less than optimal time on that project. CAB can be very nice to work with, but it's easy to create a total mess as well.

    Good Luck! 

     

    Monday, November 12, 2007 9:05 PM
  • Jack, looking at your example code, you shouldn't complain about the MVP pattern. It's not really about MVP. It's about decoupling. Even if they don't use MVP, they will probably execute those workflow in the view itself, instead of the controller/presenter.

    I had to went through similar code before (but probably in a smaller scale) and it's really a pain to find where is the code... but one you find how the flows work, it's pretty simply afterward... and you better document the work flow afterward to save the next developers time to dig up the code...
    Monday, November 12, 2007 9:25 PM
  •  ittybitty wrote:
    I think the main issue is not the patterns, but the fact that the development tools just haven't caught up with the extra levels of abstraction, making it more difficult for developers to do their jobs in most cases, rather than easier. In Visual Studio there is no easy way to trace through the code. You really have to hold the whole application in your head to make anything happen.

     

    i'm not sure that any IDE could do a better job. Most patterns are themselves simply an idea of how you could structure your code. The reason that i have to write the code (rather than using an object that someone already wrote for me), is that the situation is too specific - and making an object wouldn't be very reusable.

     

    To me, this almost by definition means that no IDE can help you - you have to structure your code in a certain way, the IDE cannot know what that structure is.

     

     

    Unfortunatly, people then try to round up all that pesky boilerplate code that the pattern requires - and they create a framework. A framework is the opposite of an object (or library). You call objects - frameworks call you. This then requires the developer to have intimate knowledge of everything that was abstracted and encapsulated by the framework so that he can then give the framework what it wants, when it wants, in the order it wants.

     

     

    i cannot picture what an IDE could do to help program with a framework.
    Wednesday, November 14, 2007 5:04 PM
  •  Kim Major wrote:

    I have been working on CAB (SCSF actually) projects and what you describe is IMHO a tooling problem and not a problem with MVP per-se.

     

    The reason i pick on MVP when i'm seeing CAB is that CAB is an implementation of the MVP design goals. i personally do not like splitting code up; the way that is being advocated.

     

    Years ago we had a design pattern to fill a listview with database records using a threaded fetch. The problem was that the code for this "one screen" was split up into two files.  And even though "we all knew" where the listview filling code was, it was still a pain to have to deal with it, maintain it, read it, follow it, debug it, and even write it in the first place.

     

    That model was thrown away for a much simpler, more managable one: the code for the form is in the form - that's where it is. And if you want to find it, you find it there.

     

     

    Also, experience has told me that creating an interface just to separate methods from code is a poor design idea. Interfaces are useful where they are needed - ensuring that an object's virtual method table is invariant - making changes to the implemention object possible. Or, when accessing objects that live on a remote machine - the remoting engine can quietly replace the object that implements the interface with whatever it wants.

     

    These were technical problems that got technical solutions.

     

     

    Using interfaces where they are not required is not a solution to any problem that we have. It simply does not happen where we might use different objects to implement the same interface. And it simply does not happen where one developer who did the "back end" code just has to declare and interface and the UI guy simply has to call the methods on the interface. This just doesn't happen, i am the UI guy and the back-end guy (for any given module).

     

     

    The only, only, only, value i can see in MVP, that our current method cannot do, is to enable more kinds of unit testing.  Right we only test deterministic functions (this input should give this output). We don't test screen processes (where the test code fakes a click on the Add button, fakes typing in the edit box, fakes hitting the Save button). We don't do this kind of unit testing - we simply don't. We probably don't do it because we don't use MVP.

     

    So when we have to ask ourselves, is the additional kinds of unit testing provided by structuring our code in an MVP pattern offset by the problems of designing, writing, maintaining, debugging MVP code? The answer is, of course, no.

    Wednesday, November 14, 2007 5:24 PM
  •  Kim Major wrote:

     tooling problem and not a problem with MVP per-se.

     

    Another real-world example if why MVP is annoying on deal with on a minute-by-minute basis:

     

    void cmbCarousel_KeyUp(object sender, System.Windows.Forms.KeyEventArgs e)

    {

    if (e.KeyCode.Equals(System.Windows.Forms.Keys.Tab) || e.KeyCode.Equals(System.Windows.Forms.Keys.Enter))

    {

     

    Now focus only on the cmbCarousel. This event handler is the KeyUp event handler for the cmbCarousel control on the form. Based on the name, one would guess (i have) that it's a combo-box. But i don't know which combo-box, so i instinctivly want to push F7 to toggle to the form so i can find the "Carousel combo box", and then i'll be able to appreciate what the code is trying to do based on what combo box it is.

     

    But when i do push F7, of course the form doesn't appear. It's then i remember that although i'm in the code that runs the view, it's not linked to the view file in the same way that the view is linked to the form.

     

    So then i have to navigate the Solution Explorer, figure out what file i'm in, find the matching presenter, then i can see what combo box it is, understand what it's probably going to be trying to do in it's handler. Then i have to find the presenter code file again, and hope that the cursor position didn't change.

     

     

     

    Here's a serious question. Has anyone ever considered the possiblity that the "View" code has already been wrapped up by Microsoft into the WinForm controls? And then i can put my "Presenter" code in the MyForm.cs code file. That still leaves a whole separate .resx Form file. And so i get some of the theoretical advanges that MVP tries to achieve:

     

    1. The UI develper can manipulate controls in the .resx file

    2. The business developer can manipulate code that runs the view in the .cs file.

    3. Microsoft has already created the abstraction between the controls and the UI.

     

    So now all that pesky UI code is in the .resx file - right where everyone "knows" it is. The presenter code, that tells the UI what to do is located all in the .cs file - right where everyone "knows" it is. And the methods and procedures for the presenter to make the UI do stuff is all located inside the Button, ComboBox, ListView .NET objects.

     

    And so if i argued it right, i already am doing MVP even through i'm not doing MVP like it was documented by the SmallTalk guys.

     

     

     

    Kim,

    i'll use an example from your MVP coderush video. During the OnLoad event of the form, you call the ViewReady method of the presenter - you essentially throw a "ViewReady" event (which the Presenter is listening for). The presenter then does a method call back to the view. The .NET WinForms framework is already doing the work to throw a ViewReady event. The IDE gives you a convient way to find that event and write code that happens in response. Why not use the OnLoad event of the form as your ViewReady event, and then place the code to call another method inside the Create handler?

     

    If you pretended that Microsoft called the event OnViewReady rather than OnLoad, you'd put the presenter code in the .cs file and be happy with it.

     

    It seems that all View code is duplicating what was already done by Microsoft - they wrote all the View code for you. We just need to write the Presenter code, and place it in the forms .cs file - which is where the presenter code goes.

     

    I

    Wednesday, November 14, 2007 6:43 PM
  • Stumbled into code:

     

    Code Block

    void cmbResponsibility_KeyUp(object sender, System.Windows.Forms.KeyEventArgs e)

    {

    ...

     

     

    Huh? What combo box is this? 

     

    Press F7

     

    Nothing happens.

     

    Huh? What file am i in?

     

    InspectionPresenter.cs

     

    Oh yeah, model view presenter. i need to choke someone's tongue out. Ugh.

    Tuesday, November 20, 2007 2:26 PM
  • i just counted it.  It's 54 files for this one screen.

     

    The Files (Sung to the tune of the Twelve Days of Christmas)

     

    There's 12 "event args" code files.

     

    There's 11 constants files.

     

    Theres 9 "smart parts" which requires two files each (view and presenter).

     

    There's 6 files for the three "services" (interface file for each service).

     

    There's 4 for the workflows to drive the UI (two workflows with two files in each)

     

    There's 3 "UI Controls"

     

    There's 2 CAB control files (Module.cs and ModuleController.cs)

     

    And a partridge in a pear tree.

    Tuesday, November 20, 2007 2:39 PM
  • Code Block

    View.cmbproductionshift.KeyUp += new System.Windows.Forms.KeyEventHandler(cmbproductionshift_KeyUp);

     

    void cmbCarousel_KeyUp(object sender, System.Windows.Forms.KeyEventArgs e)

    {

      ...

    }

     

     

     

    Am i the only person who sees it? Does everyone actually think all this is a good idea?

    Wednesday, November 21, 2007 8:57 PM
  • I worked on an application before where the base presenter class subscribes to a keyboard event in the base view class. The base presenter class handles most of the generic short cut key functions and it's kind of convenience when you have over 100 screens and you don't need to code the short cut..


    Another thing .... having a combox exposed in the view interface is really really bad practice... the presenter shouldn't know what controls a view have....
    Wednesday, November 21, 2007 10:30 PM
  • Jack,

     

    I have had the same thoughts myself Smile historically I use to write desktop apps using win32 API calls and then moved onto using MFC with C++ and then onto .Net (winForms & asp.net). To me the use of MFC & .Net winforms is a kind of MVC implementation because it abstracts you away from having to deal with the win32 API calls to create\manipulate at a low level dialogs, buttons, list, combos etc.

     

    The main reason I think this is because the frameworks (MFC & .Net winforms) both encapsulate operations on the  controls into events you are nofitied about. If you have already seperated out your business logic into a a domain model and all you are doing is responding to user interaction with the UI then I don't see why you shouldn't place simple UI logic in the form.

     

    I have also worked on projects that had concrete implementations of the MVC\MVP patterns and in some circumstances they were justified in using these patterns - mainly the ones that had COMPLICATED duplicate UI logic across mutliple screens that could in theory cause a 'ripple effect' in the UI when certain values are changed.

     

    But I class a lot of use of 'patterns' a case of 'all the gear but know idea'...

     

    A lot of devs use patterns becuase they think it makes them better devs - it's that simple. They don't realise you have to know 'how' to use the pattern to make you a better dev...

     

    Ollie

     

    Thursday, November 22, 2007 1:00 PM
  •  kenny ng wrote:
    I worked on an application before where the base presenter class subscribes to a keyboard event in the base view class.

     

    That must have been painful to deal with.

    Another thing .... having a combox exposed in the view interface is really really bad practice... the presenter shouldn't know what controls a view have....

     

    i didn't write this, i just have to deal with it.

    Thursday, November 22, 2007 3:01 PM
  •  kenny ng wrote:
    having a combox exposed in the view interface is really really bad practice... the presenter shouldn't know what controls a view have....

     

    See, i didn't know that. Is there a book or resource that explains these sort of details of MVP?

     

    Most seem to talk about code domains.

    Friday, November 23, 2007 6:49 PM
  • I think MVC/MVP is a very specific pattern than can be applied to very few real world cases. It seems to taut the following benefits:
    - Seperation of business logic from UI
    - This seperation allows for easier unit testing
    - This seperation reduces duplicate code and makes maintenance easier
    - The extra layer of abstraction between the business logic and the UI allows them to be decoupled
    - This decoupling allows the 2 to change independently (to some degree)
    - And most importantly, it allows you to define multiple views easily. E.g., if you need a web and winform UI implementation for a given set of business objects.

     

    Now, the problem with this is, that the last 3 benifits are rarely needed, and the first 3 can be achieved via any halfway descent layered architecture. If you have the following layers...
    - Endpoints (UI or service)
    - Business (business logic and business entity [data classes])
    - Data (data access components and utilities)

    ...then you can design cohesive objects, and have no business logic in the UI. You can still reuse your business logic from multiple UIs or services. These UIs and services can just directly use the business layer objects (or indirectly use them via services). We have no need for the extra complexity that comes from MVC because we do not need multiple views. A given UI is highly coupled to the data that it displays, regardless of how many abstraction layers you put between.

     

    So, to summarize my opinion, I think MVC is only really useful over other simpler architectures if you really need multiple views. Any descent layered architecture gives you the other benifits such as:
    - responsibility based class design (high cohesion)
    - ability to unit test (since the business logic is in separate classes from UI)
    - multiple 'endpoints' like UIs and services can reuse the same business logic

     

    I do think the above benifits are valuable. They help with regards to the quality and maintainability of the code. And, it is much much simpler. Many people are realizing complexity is enemy number one, and you should only introduce a more complex solution if there is a really good reason to do so.

     

    Here's a quick example of what an event handler might look like with a simple layered architecture:

    Code Block

    cmdUpdate_Click(object sender, EventArgs e)
    {

    //Update our business entity based on form...
    //alternatively, this could be achieved via some form of binding.
    _myCustomer.Name = txtName.Text;
    _myCustomer.Age = Convert.ToInt32(txtAge.Text);

     

    //Validate using validation business objects...
    //alternatively, the business entity might have validation logic bult in.
    if(!CustomerValidator.Validate(_myCustomer))
    {

    //Could pull specific msg from validator here if we wanted

    MessageBox.Show("Invalid Input");
    return;

    }

     

    //Perform business logic on business entity

    using(MyBusinnesObject bus = new MyBusinessObject())
    {

    bus.UpdateCustomer(_myCustomer);

    }

    }

     

     

    There are other variations you could use, but the main point is that we are not needlessly introducing complexity through an additional abstraction layer that is only really needed if you have multiple views. Each UI or service that uses a given set of business logic is coupled to that business logic to some degree (based on screen context, data displayed, services offered, etc.), so just take the benifits of a layered approach and don't introduce the complexity of MVC/MVP if you don't need to.

     

    Now, for the qualification. I'm no MVC/MVP expert, so if there is some other key benifit that MVC/MVP has over general layered architectures, other than multiple views, please let me know. I too am curious to know what the benifit is, or if many people have mistakenly used it when all they were really after were the first 3 benifits, that can be achieved via simpler architectures.

    Thursday, December 20, 2007 8:46 PM
  •  Todd F. Snyder wrote:

    Over the years, I have used the MVP/MVC pattern on several (Web and WinForm) projects. There are several good reasons for using these patterns and most projects would benefit from using these and other patterns.

    First, is helps to clarify that Model View Presenter (MVP) and Model View Controller (MVC) are two entirely different patterns that solve the same problem .Both patterns have been in use for several years and focus on separating the view (UI) from the model (Business Classes).

    Using the MVC pattern developers create controller classes that are responsible for responding to UI events and updating the model according to the action (event) invoked. While using the MVP pattern developers create presenter classes that do basically the same thing; but, also include the use of a .Net interface to talk to the view. The use of this interface is the major differences between the patterns and makes the presenter generally more loosely coupled then a controller. In some advanced scenarios you need to have both presenters and controller. In those cases the classes work together to isolate the view from the model.

    Benefits of using either pattern

    ·         Loose coupling – The presenter/controller are an intermediary between the UI code and the model

    ·         Clear separation of concerns/responsibility

    o    UI (Form or Page) – Responsible for rending UI elements

    o    Presenter/controller – Responsible for reacting to UI events and interacting with the model

    o    Model – Responsible for business behaviors and state management

    ·         Test Driven – By isolating each major component (UI, Presenter/controller, and model) it is easier to write unit tests. This is especially true when using the MVP pattern which only interacts with the view using an interface.

    ·         Code Reuse – By using a separation of concerns/responsible design approach you will increase code reuse. This is especially true when using a full blown domain model and keeping all the business/state management logic where it belongs.

    ·         Hide Data Access – Using these patterns forces you to put the data access code where it belongs in a data access layer. There a number of other patterns that typical works with the MVP/MVC pattern for data access. Two of the most common ones are repository and unit of work. (See Martin Fowler – Patterns of Enterprise Application Architecture for more details)

    ·         Adaptable to change – I have been in this business for over 12 years and two things have changed more than any other (UI and Data Access). For example in .Net today we have several UI (WinForm, ASP.Net, AJAX, SilverLight, and WPF), and data access (DataSets, DataReaders, XML, LINQ, and Entity Framework) technologies. By using MVP or MVC it is easier to plug in any of these UI or data access technologies and even possible to support more than one at a time.

    To recap the MVP and MVC are two separate patterns that address the same problem. Both patterns focus on isolating the UI from the model and these patterns are more adaptable to change then traditional approaches. I hope you found this helpful.

    Wednesday, July 30, 2008 10:10 AM
  •  Hi  i am using MVP in my application .when i executes a application Presenter events are repeated twice how can i stop this execution pls help me it's urgent

    Wednesday, July 30, 2008 10:32 AM
  • Well Its Very Much Possible To Achieve Extensibility Of Codes Without Using MVC/MVP.

    Its Just Depend Upon How You Code.


    Mark Post As Answer If It Helped You and Also Take Some Time Out To Mark The Thread Resolved.
    Wednesday, April 13, 2011 5:41 PM