How to store business logic in domain object? - model-view-controller

I will display a grid of a view model class M {string A, int B, float C, int D, .....}:
Render the number in red if it's negative.
Highlight the background of the cell if A is in 'xxx', 'zzz' and B = 0 or D > 200...
Set the background of the row to grey if E > 100 and F < 0....
Are these considered business logic? Where to put these logic if they are? For (3), I guess a new read-only property can be created in in the view model? But it make the M not POJO/POCO any more? I read that the business logic should be in domain object. Is the domain object implemented using POJO/POCO?
Is there any code sample shows how the business logic is stored in domain objects?

There are several ways to achieve what you are trying to do. You mention the term 'View-Model' a few times in your description, which makes me think you are trying to use the design pattern 'MVVM' (Model-View-ViewModel), which is popular when using WPF or Silverlight technology due to things like it's support for databinding against the view, but can be extended to other technologies too.
In MVVM, the tiers are split into the Model, the View-Model and the View.
The Model is essentially your domain, and is used only for Domain specific modelling. Your applications entities should live here, but there should be no calculations, or manipulation of the domain entities. eg. If it was a cycling domain, your 'Bike' and 'Rider' classes should live here, but there should be no code relating to calculating the race winners, or what colour to display the winner in your application GUI.
The View-Model is where you prepare your domain entities to be presented into your View (User interface). You pretty much achieve this by wrapping your domain entities into new classes, that take the domain object in the constructor, but then expose, or translate the existing properties into the ones you want to be displayed in the View. In the cycling analogy your Bike object might have Make, Model, Cost, RRP, TimeBuilt properties, so in the view model I would expose the Make, Model properties, but then translate the Cost and RRP along with margin to come up with the retail price (as seen on the front end).
The View, as you might have guessed is where this information is displayed. This might be a desktop, mobile or web front end - it doesn't really matter. This is also where any rendering of the UI should be achieved. If I wanted to highlight great deals to my customers, and colour any Bikes with very good retail prices in green - I would do it here.
So, when relating to your example, formatting how the object is displayed should be achieved in the View. Even if your not using MVVM, you can achieve very similar results by extending your domain objects into Wrapper classes to be deployed and manipulated. Your rules such as
Highlight the background of the cell if A is in 'xxx', 'zzz' and B = 0 or D > 200
can be modeled in a boolean on your view model class, giving you the effect you need, without polluting your domain objects with non-specific code.
Regardless of architectural choice, (MVC, MVP, MVVM etc) these are good guidelines to develop by, as they deploy separation of concerns between the layers of your application.

You could store the output of all your 3 calculations as properties on you object, then pass the calculated object to your view.
For example on point 1 render the number if it is negative. this color red could be passed to the view. the actual calculation that determines the color to be red could happen in your biz logic layer.
Please let me know if this helps.

The term "view model" is wrong. View and Model are two separate things, each dealing with a distinct/separate concern of the application: model encapsulating business logic, view handling presentation/display. In simple terms, model is your domain object.
What you have shown in your example, is presentation-related. It belongs to view, not to model.

Related

Should I move some Properties into a Model?

I am using MVVM light and I have a View Model but I am not sure if I should move some of the properties out as I got quite a few on them now.
Eventhough they are simple properties for the most part,my view model is kinda getting long(437 lines of properites)
I am wondering if it would make some sense to move out some of the properties out into a model, in a sense making it easier to find the more important properties.
I have 5 controls on my wp7 view.
5 properties for IsEnabled (if location service is turned off then all properties are disabled)l
6 properties to store the values that the user selects
3 relay commands.
1 property to hide/show a control based on what is selected.
I am still working on the page so there probably will be more in the end.
I am wondering if I should take out the 6 properties that would store the information from the user and make it into a model.
Then just have stuff like relayCommands, Visablity, Enabled stuff in the ViewModel and have one property that of course has my Model class.
Having lean view models are always a good thing. It makes it easier to manage and understand for other developers (or yourself) later on.
Pulling your domain specific data into models is always a good thing. Say you wanted to reference that user in a different view later on - with everything piled into your view model, you'd have to replicate a lot of code every time you make a new view model. Not good.
If you pull said user into it's own domain model object, then you could simply reference the user with a single line of code (and easily access its properties through setters and getters.
Remember, MVVM stands for model, view, viewmodel, and without the models, you're stuck with potentially almost chaotic code and lots of replication. Replication of code leads to human errors while copying and a ton of other headaches.
now that's the general idea. I understand you're asking about how you should manage your "temporary" properties (which the users fills in), and I have to say the same rules apply here as above. Having more than a few models aren't a bad thing at all (if working in an enterprise environment has taught me anything, it's not being afraid of splitting up code into manageable sizes).
Another approach you could use is creating a parent class for your view model to inherit from. Put any "i'll need these for all my views" properties here, and the specific information is left in the view model inheriting the superclass.
A third thing I noticed is that you have an "isEnabled" property for each of your controls. If you have an "all or nothing" scenario, like you portray, you only need one. Bind that property up to the visibility of all your elements, and ease your visibility management sixfold =)
Hope this cleared a few things up! =)
Whatever is for the view should be in your viewModel. Ideally you would not want to update your model just because your view required too. Any such things would go into the ViewModel.
As suggested above you could break up the view models. There need not be a one-to-one mapping of views to view models. A view can be composed of many view models.
By 437 lines of properties do you mean to say that you have 437 properties? If that is the case that is way too much for your view in itself and I would reconsider breaking up your views into more simpler ones for usability.
Here are a couple of common scenarios that we normally come across while using MVVM

Should models or views generate strings for humans?

Here is an issue I've confronted in multiple user-facing applications: a program contains components for graphical rendering of data, (call them views) and other components for managing those data (call them models). Some of those data are in the form human friendly text, often key value pairs such as
System Load: 20%
Running Time: 20mins 30sec
But which software component should be responsible for constructing the text strings? You could argue
The model: should choose the text while leaving the view to display it. This way the views don't have to know exactly which data are provided, and (probably) lets the model expose only a small API. Also it means that the text stays consistent across multiple views (or UI toolkits). This ways views don't have to worry about i18n.
The view: should do it because this is a UI issue, not part of the business logic. After all, the choice of text is not always cleanly separable from rendering. This way models don't have to worry about i18n.
How should I settle, or think about this division of labour? Any ideas?
Note 1: I don't think this issue is restricted to MVC designs, although that's where I get my terminology.
Note 2: While researching this question I stumbled across Presenters, and ViewModels. Are they supposed to do this kind of work, and when is such a proper/complicated solution worthwhile, and when is it OK to just do it in the Model or View.
Taking this from an MVC perspective, if I have data to display in my view I will (almost) always create a viewmodel which the view inherits from, with the viewmodel properties of the correct type for the data. e.g. in your example above I would have SystemLoad as decimal, and running time as a number of seconds. I believe it is then the responsibility of the view to determine how that data is displayed (how the user VIEWS it).
Using the ViewModel approach makes it very easy to define multiple views to represent the same data. A controller need only know to supply and receive a specified class - the ViewModel - which can then be passed to whichever the most appropriate view is to be rendered. This rendering could be rich HTML for full browsers, stripped down for mobiles, or even a JSON response for an API, either way the controller need not change.
WRT to the original question, this is just an example of justification for leaving the formatting to the View. Whether you use viewmodels or not, this logic does not belong in the controller
As a general rule I would suggest leaving to models anything that is abstract and to the view, all the specific. For example, a model would have system_load: 0.20 and running_time: 1860 but y our view would turn these two values into actual useful, viewable information.

MVC best practice question

I have a question regarding MVC design, based on the Stanford iPhone lectures.
I have 3 classes;
Polygon - this holds information like number of sides and so on. This is my Model class
Controller - this responds to things like button presses in the view and then calles methods in the model to increase and decrease the number of sides etc. This is my controller (surprise!)
View - For this question the view will be a Class representing a single view, which draws the polygon to screen.
My question is what is the best way for the View class to obtain information pertaining to the Polygon model class? Although this is trivial for this example I'm hoping that the answer wil help me when building more complicated applications. Options I have;
1) Pass the instance of the Polygon class to the View so the view has a pointer to it. Then I can just call refresh at any time and the view will know what to do. This is what i would usually do but seens to break the MVC approach as the View and Model seem to be bypassing the controller, which makes me think this may not be the best way.
2) Have a redraw(...) method in the view, which takes as its args whatever new information received. This seems clean but would not scale well i would think.
Any advice would be great. As I say usually I would do option one, but would love someone to tell me something to improve the way i think about this....
Thanks!
The essential thing here is coupling. If it’s too tight, the design will suffer, you will repeat yourself and the code will be hard to maintain. If it’s too loose, it makes simple things too hard to manage. If you want to draw a simple polygon based on some model, you should have the model at hand, for it would be crazy to pull all the vertices through a controller. After all, the view is specifically written to display a polygon, so that it is perfectly natural to have a pointer to its representation.
What view does not care about is the context, the “life story” of the displayed object. It might come from the network, it may change soon, it may become twice as big when you click on it. The view does not care. If you click on it, the view can report the event back to controller and does not care about it any more. If the object changes, the controller will tell the view to update.
I don’t think there is a hard rule for designing such relationships, but the point is simple: keep loose coupling without sweating the details too much. It often helps me to think about testing and changes. Can I isolate the model for testing? Can I use a completely different view without changing the other parts? Could I write a different user interface based on the same model? How about a different “skin”? How much would I have to rewrite?
your view should be doing nothing but showing the view. so if you need to show updated information in the view, you either do it from cache (which isn't really applicable here, but I'm throwing that out because its something I've been doing lots lately with web stuff), or you re-engage the controller and get the controller to call the view again with updated data about the model.
so technically, your second option is the more correct one. the view should redraw itself by calling the controller and asking it for updated information.
Model is data. Controller is logic. View is display.
As such, the Model be like a data clerk. The controller should be like a administrator or team leader in an office. And the view should be like a news reporter reading a teleprompt reader.
The controller can boss everyone around, and controls the data entered and the text on the teleprompter - and outsources the actual work to the model (for data) and view (for display).
As such, to answer your question. The view should just do echo $this->view->myPentagon->someAttribute. The controller fetches the myPentagon object from the model, and assigns it to the view object. The model handles the data structure and database api. The view handles the display. The controller tells the view when to display.

What is the difference between MVC and MVVM? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
Is there a difference between the standard "Model View Controller" pattern and Microsoft's Model/View/ViewModel pattern?
MVC/MVVM is not an either/or choice.
The two patterns crop up, in different ways, in both ASP.Net and Silverlight/WPF development.
For ASP.Net, MVVM is used to two-way bind data within views. This is usually a client-side implementation (e.g. using Knockout.js). MVC on the other hand is a way of separating concerns on the server-side.
For Silverlight and WPF, the MVVM pattern is more encompassing and can appear to act as a replacement for MVC (or other patterns of organising software into separate responsibilities). One assumption, that frequently came out of this pattern, was that the ViewModel simply replaced the controller in MVC (as if you could just substitute VM for C in the acronym and all would be forgiven)...
The ViewModel does not necessarily replace the need for separate Controllers.
The problem is: that to be independently testable*, and especially reusable when needed, a view-model has no idea what view is displaying it, but more importantly no idea where its data is coming from.
*Note: in practice Controllers remove most of the logic, from the ViewModel, that requires unit testing. The VM then becomes a dumb container that requires little, if any, testing. This is a good thing as the VM is just a bridge, between the designer and the coder, so should be kept simple.
Even in MVVM, controllers will typically contain all processing logic and decide what data to display in which views using which view models.
From what we have seen so far the main benefit of the ViewModel pattern to remove code from XAML code-behind to make XAML editing a more independent task. We still create controllers, as and when needed, to control (no pun intended) the overall logic of our applications.
The basic MVCVM guidelines we follow are:
Views display a certain shape of data. They have no idea where the data comes from.
ViewModels hold a certain shape of data and commands, they do not know where the data, or code, comes from or how it is displayed.
Models hold the actual data (various context, store or other methods)
Controllers listen for, and publish, events. Controllers provide the logic that controls what data is seen and where. Controllers provide the command code to the ViewModel so that the ViewModel is actually reusable.
We also noted that the Sculpture code-gen framework implements MVVM and a pattern similar to Prism AND it also makes extensive use of controllers to separate all use-case logic.
Don't assume controllers are made obsolete by View-models.
I have started a blog on this topic which I will add to as and when I can (archive only as hosting was lost). There are issues with combining MVCVM with the common navigation systems, as most navigation systems just use Views and VMs, but I will go into that in later articles.
An additional benefit of using an MVCVM model is that only the controller objects need to exist in memory for the life of the application and the controllers contain mainly code and little state data (i.e. tiny memory overhead). This makes for much less memory-intensive apps than solutions where view-models have to be retained and it is ideal for certain types of mobile development (e.g. Windows Mobile using Silverlight/Prism/MEF). This does of course depend on the type of application as you may still need to retain the occasional cached VMs for responsiveness.
Note: This post has been edited numerous times, and did not specifically target the narrow question asked, so I have updated the first part to now cover that too. Much of the discussion, in comments below, relates only to ASP.Net and not the broader picture. This post was intended to cover the broader use of MVVM in Silverlight, WPF and ASP.Net and try to discourage people from replacing controllers with ViewModels.
I think the easiest way to understand what these acronyms are supposed to mean is to forget about them for a moment. Instead, think about the software they originated with, each one of them. It really boils down to just the difference between the early web and the desktop.
As they grew in complexity in the mid-2000s, the MVC software design pattern - which was first described in the 1970s - began to be applied to web applications. Think database, HTML pages, and code inbetween. Let's refine this just a little bit to arrive at MVC: For »database«, let's assume database plus interface code. For »HTML pages«, let's assume HTML templates plus template processing code. For »code inbetween«, let's assume code mapping user clicks to actions, possibly affecting the database, definitely causing another view to be displayed. That's it, at least for the purpose of this comparison.
Let's retain one feature of this web stuff, not as it is today, but as it existed ten years ago, when JavaScript was a lowly, despicable annoyance, which real programmers did well to steer clear of: The HTML page is essentially dumb and passive. The browser is a thin client, or if you will, a poor client. There is no intelligence in the browser. Full page reloads rule. The »view« is generated anew each time around.
Let's remember that this web way, despite being all the rage, was horribly backward compared to the desktop. Desktop apps are fat clients, or rich clients, if you will. (Even a program like Microsoft Word can be thought of as some kind of client, a client for documents.) They're clients full of intelligence, full of knowledge about their data. They're stateful. They cache data they're handling in memory. No such crap as a full page reload.
And this rich desktop way is probably where the second acronym originated, MVVM. Don't be fooled by the letters, by the omission of the C. Controllers are still there. They need to be. Nothing gets removed. We just add one thing: statefulness, data cached on the client (and along with it intelligence to handle that data). That data, essentially a cache on the client, now gets called »ViewModel«. It's what allows rich interactivity. And that's it.
MVC = model, controller, view = essentially one-way communication = poor interactivity
MVVM = model, controller, cache, view = two-way communication = rich interactivity
We can see that with Flash, Silverlight, and - most importantly - JavaScript, the web has embraced MVVM. Browsers can no longer be legitimately called thin clients. Look at their programmability. Look at their memory consumption. Look at all the Javascript interactivity on modern web pages.
Personally, I find this theory and acronym business easier to understand by looking at what it's referring to in concrete reality. Abstract concepts are useful, especially when demonstrated on concrete matter, so understanding may come full circle.
MVVM Model-View ViewModel is similar to MVC, Model-View Controller
The controller is replaced with a ViewModel. The ViewModel sits below the UI layer. The ViewModel exposes the data and command objects that the view needs. You could think of this as a container object that view goes to get its data and actions from. The ViewModel pulls its data from the model.
Russel East does a blog discussing more in detail Why is MVVM is different from MVC
For one thing, MVVM is a progression of the MVC pattern which uses XAML to handle the display. This article outlines some of the facets of the two.
The main thrust of the Model/View/ViewModel architecture seems to be that on top of the data (”the Model”), there’s another layer of non-visual components (”the ViewModel”) that map the concepts of the data more closely to the concepts of the view of the data (”the View”). It’s the ViewModel that the View binds to, not the Model directly.
Microsoft provided an explanation of the MVVM Pattern in the Windows environment here.
Here's a crucial section:
In the Model-View-ViewModel design pattern, an app is composed of
three general components.
Model: This represents the data model that your app consumes. For example, in a picture sharing app, this layer might represent the
set of pictures available on a device and the API used to read and
write to the picture library.
View: An app typically is composed of multiple pages of UI. Each page shown to the user is a view in MVVM terminology. The view is
the XAML code used to define and style what the user sees. The data
from the model is displayed to the user, and it’s the job of the
ViewModel to feed the UI this data based on the current state of the
app. For example, in a picture sharing app, the views would be the UI
that show the user the list of albums on the device, the pictures in
an album, and perhaps another that shows the user a particular
picture.
ViewModel: The ViewModel ties the data model, or simply the model, to the UI, or views, of the app. It contains the logic with
which to manage the data from the model and exposes the data as a set
of properties to which the XAML UI, or views, can bind. For example,
in a picture sharing app, the ViewModel would expose a list of albums,
and for each album expose a list of pictures. The UI is agnostic of
where the pictures come from and how they are retrieved. It simply
knows of a set of pictures as exposed by the ViewModel and shows them
to the user.
I thought one of the main differences was that in MVC, your V reads your M directly, and goes via the C to manipulate the data, whereas in MVVM, your VM acts as an M proxy, as well as providing the available functionality to you V.
If I'm not full of junk, I'm surprised no one has created a hybrid, where your VM is merely a M proxy, and C provides all functionality.
The other answers might not be easy to understand for one who is not much familiar with the subject of architectural patterns. Someone who is new to app architecture might want to know how its choice can affect her app in practice and what all the fuss is about in communities.
Trying to shed some light on the above, I made up this screenplay involving MVVM, MVP and MVC. The story begins by a user clicking on the ‘FIND’ button in a movie search app… :
User: Click …
View: Who’s that? [MVVM|MVP|MVC]
User: I just clicked on the search button …
View: Ok, hold on a sec … . [MVVM|MVP|MVC]
( View calling the ViewModel|Presenter|Controller … ) [MVVM|MVP|MVC]
View: Hey ViewModel|Presenter|Controller, a User has just clicked on the search button, what shall I do? [MVVM|MVP|MVC]
ViewModel|Presenter|Controller: Hey View, is there any search term on that page? [MVVM|MVP|MVC]
View: Yes,… here it is … “piano” [MVVM|MVP|MVC]
—— This is the most important difference between MVVM AND MVP|MVC ———
Presenter|Controller: Thanks View,… meanwhile I’m looking up the search term on the Model, please show him/her a progress bar [MVP|MVC]
( Presenter|Controller is calling the Model … ) [MVP|MVC]
ViewModel: Thanks, I’ll be looking up the search term on the Model but will not update you directly. Instead, I will trigger events to searchResultsListObservable if there is any result. So you had better observe on that. [MVVM]
(While observing on any trigger in searchResultsListObservable, the View thinks it should show some progress bar to the user, since ViewModel would not talk to it on that)
——————————————————————————————
ViewModel|Presenter|Controller: Hey Model, Do you have any match for this search term?: “piano” [MVVM|MVP|MVC]
Model: Hey ViewModel|Presenter|Controller, let me check … [MVVM|MVP|MVC]
( Model is making a query to the movie database … ) [MVVM|MVP|MVC]
( After a while … )
———— This is the diverging point between MVVM, MVP and MVC ————–
Model: I found a list for you, ViewModel|Presenter, here it is in JSON “[{“name”:”Piano Teacher”,”year”:2001},{“name”:”Piano”,”year”:1993}]” [MVVM|MVP]
Model: There is some result available, Controller. I have created a field variable in my instance and filled it with the result. It’s name is “searchResultsList” [MVC]
(Presenter|Controller thanks Model and gets back to the View) [MVP|MVC]
Presenter: Thanks for waiting View, I found a list of matching results for you and arranged them in a presentable format: [“Piano Teacher 2001″,”Piano 1993”]. Also please hide the progress bar now [MVP]
Controller: Thanks for waiting View, I have asked Model about your search query. It says it has found a list of matching results and stored them in a variable named “searchResultsList” inside its instance. You can get it from there. Also please hide the progress bar now [MVC]
ViewModel: Any observer on searchResultsListObservable be notified that there is this new list in presentable format: [“Piano Teacher 2001″,”Piano 1993”].[MVVM]
View: Thank you very much Presenter [MVP]
View: Thank you “Controller” [MVC] (Now the View is questioning itself: How should I present the results I get from the Model to the user? Should the production year of the movie come first or last…?)
View: Oh, there is a new trigger in searchResultsListObservable … , good, there is a presentable list, now I only have to show it in a list. I should also hide the progress bar now that I have the result. [MVVM]
In case you are interested, I have written a series of articles here, comparing MVVM, MVP and MVC by implementing a movie search android app.
MVC is a controlled environment and MVVM is a reactive environment.
In a controlled environment you should have less code and a common source of logic; which should always live within the controller. However; in the web world MVC easily gets divided into view creation logic and view dynamic logic. Creation lives on the server and dynamic lives on the client. You see this a lot with ASP.NET MVC combined with AngularJS whereas the server will create a View and pass in a Model and send it to the client. The client will then interact with the View in which case AngularJS steps in to as a local controller. Once submitted the Model or a new Model is passed back to the server controller and handled. (Thus the cycle continues and there are a lot of other translations of this handling when working with sockets or AJAX etc but over all the architecture is identical.)
MVVM is a reactive environment meaning you typically write code (such as triggers) that will activate based on some event. In XAML, where MVVM thrives, this is all easily done with the built in databinding framework BUT as mentioned this will work on any system in any View with any programming language. It is not MS specific. The ViewModel fires (usually a property changed event) and the View reacts to it based on whatever triggers you create. This can get technical but the bottom line is the View is stateless and without logic. It simply changes state based on values. Furthermore, ViewModels are stateless with very little logic, and Models are the State with essentially Zero logic as they should only maintain state. I describe this as application state (Model), state translator (ViewModel), and then the visual state / interaction (View).
In an MVC desktop or client side application you should have a Model, and the Model should be used by the Controller. Based on the Model the controller will modify the View. Views are usually tied to Controllers with Interfaces so that the Controller can work with a variety of Views. In ASP.NET the logic for MVC is slightly backwards on the server as the Controller manages the Models and passes the Models to a selected View. The View is then filled with data based on the model and has it's own logic (usually another MVC set such as done with AngularJS). People will argue and get this confused with application MVC and try to do both at which point maintaining the project will eventually become a disaster. ALWAYS put the logic and control in one location when using MVC. DO NOT write View logic in the code behind of the View (or in the View via JS for web) to accommodate Controller or Model data. Let the Controller change the View. The ONLY logic that should live in a View is whatever it takes to create and run via the Interface it's using. An example of this is submitting a username and password. Whether desktop or web page (on client) the Controller should handle the submit process whenever the View fires the Submit action. If done correctly you can always find your way around an MVC web or local app easily.
MVVM is personally my favorite as it's completely reactive. If a Model changes state the ViewModel listens and translates that state and that's it!!! The View is then listening to the ViewModel for state change and it also updates based on the translation from the ViewModel. Some people call it pure MVVM but there's really only one and I don't care how you argue it and it's always Pure MVVM where the View contains absolutely no logic.
Here's a slight example: Let's say the you want to have a menu slide in on a button press. In MVC you will have a MenuPressed action in your interface. The Controller will know when you click the Menu button and then tell the View to slide in the Menu based on another Interface method such as SlideMenuIn. A round trip for what reason? Incase the Controller decides you can't or wants to do something else instead that's why. The Controller should be in charge of the View with the View doing nothing unless the Controller says so. HOWEVER; in MVVM the slide menu in animation should be built in and generic and instead of being told to slide it in will do so based on some value. So it listens to the ViewModel and when the ViewModel says, IsMenuActive = true (or however) the animation for that takes place. Now, with that said I want to make another point REALLY CLEAR and PLEASE pay attention. IsMenuActive is probably BAD MVVM or ViewModel design. When designing a ViewModel you should never assume a View will have any features at all and just pass translated model state. That way if you decide to change your View to remove the Menu and just show the data / options another way, the ViewModel doesn't care. So how would you manage the Menu? When the data makes sense that's how. So, one way to do this is to give the Menu a list of options (probably an array of inner ViewModels). If that list has data, the Menu then knows to open via the trigger, if not then it knows to hide via the trigger. You simply have data for the menu or not in the ViewModel. DO NOT decide to show / hide that data in the ViewModel.. simply translate the state of the Model. This way the View is completely reactive and generic and can be used in many different situations.
All of this probably makes absolutely no sense if you're not already at least slightly familiar with the architecture of each and learning it can be very confusing as you'll find ALOT OF BAD information on the net.
So... things to keep in mind to get this right. Decide up front how to design your application and STICK TO IT.
If you do MVC, which is great, then make sure you Controller is manageable and in full control of your View. If you have a large View consider adding controls to the View that have different Controllers. JUST DON'T cascade those controllers to different controllers. Very frustrating to maintain. Take a moment and design things separately in a way that will work as separate components... And always let the Controller tell the Model to commit or persist storage. The ideal dependency setup for MVC in is View ← Controller → Model or with ASP.NET (don't get me started) Model ← View ↔ Controller → Model (where Model can be the same or a totally different Model from Controller to View) ...of course the only need to know of Controller in View at this point is mostly for endpoint reference to know where back to pass a Model.
If you do MVVM, I bless your kind soul, but take the time to do it RIGHT! Do not use interfaces for one. Let your View decide how it's going to look based on values. Play with the View with Mock data. If you end up having a View that is showing you a Menu (as per the example) even though you didn't want it at the time then GOOD. You're view is working as it should and reacting based on the values as it should. Just add a few more requirements to your trigger to make sure this doesn't happen when the ViewModel is in a particular translated state or command the ViewModel to empty this state. In your ViewModel DO NOT remove this with internal logic either as if you're deciding from there whether or not the View should see it. Remember you can't assume there is a menu or not in the ViewModel. And finally, the Model should just allow you to change and most likely store state. This is where validation and all will occur; for example, if the Model can't modify the state then it will simply flag itself as dirty or something. When the ViewModel realizes this it will translate what's dirty, and the View will then realize this and show some information via another trigger. All data in the View can be binded to the ViewModel so everything can be dynamic only the Model and ViewModel has absolutely no idea about how the View will react to the binding. As a matter of fact the Model has no idea of a ViewModel either. When setting up dependencies they should point like so and only like so View → ViewModel → Model (and a side note here... and this will probably get argued as well but I don't care... DO NOT PASS THE MODEL to the VIEW unless that MODEL is immutable; otherwise wrap it with a proper ViewModel. The View should not see a model period. I give a rats crack what demo you've seen or how you've done it, that's wrong.)
Here's my final tip... Look at a well designed, yet very simple, MVC application and do the same for an MVVM application. One will have more control with limited to zero flexibility while the other will have no control and unlimited flexibility.
A controlled environment is good for managing the entire application from a set of controllers or (a single source) while a reactive environment can be broken up into separate repositories with absolutely no idea of what the rest of the application is doing. Micro managing vs free management.
If I haven't confused you enough try contacting me... I don't mind going over this in full detail with illustration and examples.
At the end of the day we're all programmers and with that anarchy lives within us when coding... So rules will be broken, theories will change, and all of this will end up hog wash... But when working on large projects and on large teams, it really helps to agree on a design pattern and enforce it. One day it will make the small extra steps taken in the beginning become leaps and bounds of savings later.
Simple Difference: (Inspired by Yaakov's Coursera AngularJS course)
MVC (Model View Controller)
Models: Models contain data information. Does not call or use Controller and View. Contains the business logic and ways to represent data. Some of this data, in some form, may be displayed in the view. It can also contain logic to retrieve the data from some source.
Controller: Acts as the connection between view and model. View calls Controller and Controller calls the model. It basically informs the model and/or the view to change as appropriate.
View: Deals with UI part. Interacts with the user.
MVVM (Model View View Model)
ViewModel:
It is the representation of the state of the view.
It holds the data that’s displayed in the view.
Responds to view events, aka presentation logic.
Calls other functionalities for business logic processing.
Never directly asks the view to display anything.
MVVM is a refinement (debatable) of the Presentation Model pattern. I say debatable, because the only difference is in how WPF provides the ability to do data binding and command handling.
The viewmodel is an "abstract" model for your user interface elements. It must allow you to execute the commands, and actions in your view in a non-visual way (for example to test it).
If you have worked with MVC, you probably have sometime found useful to create model objects to reflect the state of your view, for example, to show and hide some edit dialog, etc. In that case you are using a viewmodel.
The MVVM pattern is simply the generalization of that practice to all the UI elements.
And it's not a Microsoft pattern, what appends is that WPF / Silverlight data-bindings are specially well-suited to work with this pattern. But nothing stops you to use it with java server faces, for example.
It surprises me that this is a highly voted answers without mentioning the origin of MVVM. MVVM is a popular term used in Microsoft community and it is originated from Martin Fowler's Presentation Model. So to understand the motive of the pattern and the differences with others, the original article about the pattern is the first thing to read.
Injecting Strongly Typed ViewModels into the View using MVC
The controller is responsible for newing up the ViewModel and injecting it into the View. (for get requests)
The ViewModel is the container for DataContext and view state such as the last selected item etc.
The Model contains DB entities and is very close to the DB Schema it does the queries and filtering. (I like EF and LINQ for this)
The Model should also consider repositories and or projection of results into strong types (EF has a great method... EF.Database.Select(querystring, parms) for direct ADO access to inject queries and get back strong types. This addresses the EF is slow argument. EF is NOT SLOW!
The ViewModel gets the data and does the business rules and validation
The controller on post back will cal the ViewModel Post method and wait for results.
The controller will inject the newly updated Viewmodel to the View. The View uses only strong type binding.
The view merely renders the data, and posts events back to the controller. (see examples below)
MVC intercepts the inbound request and routes it to proper controller with strong data type
In this model there is no more HTTP level contact with the request or response objects as MSFT's MVC machine hides it from us.
In clarification of item 6 above (by request)...
Assume a ViewModel like this:
public class myViewModel{
public string SelectedValue {get;set;}
public void Post(){
//due to MVC model binding the SelectedValue string above will be set by MVC model binding on post back.
//this allows you to do something with it.
DoSomeThingWith(SelectedValue);
SelectedValue = "Thanks for update!";
}
}
The controller method of the post will look like this (See below), note that the instance of mvm is automatically instanciated by the MVC binding mechanisms. You never have to drop down to the query string layer as a result! This is MVC instantiating the ViewModel for you based on the query strings!
[HTTPPOST]
public ActionResult MyPostBackMethod (myViewModel mvm){
if (ModelState.IsValid)
{
// Immediately call the only method needed in VM...
mvm.Post()
}
return View(mvm);
}
Note that in order for this actionmethod above to work as you intend, you must have a null CTOR defined that intializes things not returned in the post. The post back must also post back name/value pairs for those things which changed. If there are missing name/value pairs the MVC binding engine does the proper thing which is simply nothing! If this happens you might find yourself saying "I'm losing data on post backs"...
The advantage of this pattern is the ViewModel does all the "clutter" work interfacing to the Model/Buisness logic, the controller is merely a router of sorts. It is SOC in action.
MVVM adds the view model into the mix. This is important, as it allows you to use a lot of the binding approach of WPF, without putting all that UI specific pieces in your regular model.
I may be wrong, but I am not sure MVVM really forces the controller into the mix. I find the concept to be more in line with: http://martinfowler.com/eaaDev/PresentationModel.html. I think that people choose to combine it with MVC, not that it is built in into the pattern.
From what I can tell, the MVVM maps to the MV of MVC - meaning that in a traditional MVC pattern the V does not communicate directly with the M. In the second version of MVC, there is a direct link between M and V. MVVM appears to take all tasks related to M and V communication, and couple it to decouple it from the C. In effect, there's still the larger scope application workflow (or implementation of the use scenarios) that are not fully accounted for in MVVM. This is the role of the controller. By removing these lower level aspects from the controllers, they are cleaner and makes it easier to modify the application's use scenario and business logic, also making controllers more reusable.
MVVM
View ➡ ViewModel ➡ Model
The view has a reference to the ViewModel but not vice versa.
The ViewModel has a reference to the Model but not vice versa.
The View has no reference to the Model and vice versa.
If you are using a controller, it can have a reference to Views and ViewModels, though a Controller is not always necessary as demonstrated in SwiftUI.
Data Binding: we create listeners for ViewModel Properties so that data can flow from the view to the model through the view model. While the references go one way: View ➡ ViewModel ➡ Model, data needs to flow: View ↔ ViewModel ↔ Model. Its clear how the view gets data from the model, by reading its own properties. Data Binding is how to detect events within the view and feed them back to the model.
class CustomView: UIView {
var viewModel = MyViewModel {
didSet {
self.color = viewModel.viewColor
}
}
convenience init(viewModel: MyViewModel) {
self.viewModel = viewModel
}
}
struct MyViewModel {
var viewColor: UIColor {
didSet {
colorChanged?() // This is where the binding magic happens.
}
}
var colorChanged: ((UIColor) -> Void)?
}
class MyViewController: UIViewController {
let myViewModel = MyViewModel(viewColor: .green)
let customView: CustomView!
override func viewDidLoad() {
super.viewDidLoad()
// This is where the binder is assigned.
myViewModel.colorChanged = { [weak self] color in
print("wow the color changed")
}
customView = CustomView(viewModel: myViewModel)
self.view = customView
}
}
differences in setup
Business logic is held in the controller for MVC and the ViewModels for MVVM.
Events are passed directly from the View to the controller in MVC while events are passed from the View to the ViewModel to the Controller (if there is one) for MVVM.
Common features
Both MVVM and MVC do not allow the View to send messages directly to the Model/s.
Both have models.
Both have views.
Advantages of MVVM
Because the ViewModels hold business logic, they are smaller concrete objects making them easy to unit tests. On the other hand, in MVC, the business logic is in the ViewController. How can you trust that a unit test of a view controller is comprehensively safe without testing all the methods and listeners simultaneously? You can't wholly trust the unit test results.
In MVVM, because business logic is siphoned out of the Controller into atomic ViewModel units, the size of the ViewController shrinks and this makes the ViewController code more legible.
Advantages of MVC
Providing business logic within the controller reduces the need for branching and therefore statements are more likely to run on the cache which is more performant over encapsulating business logic into ViewModels.
Providing business logic in one place can accelerate the development process for simple applications, where tests are not required. I don't know when tests are not required.
Providing business logic in the ViewController is easier to think about for new developers.
In very short - in MVC Controler is aware of (controls) view, while in MVVM, ViewModel is unaware of who consumes it. ViewModel exposes its observable properties and actions to whoever might be interested in using it. That fact makes testing easier since there is no reference to UI within ViewModel.
Well, generally MVC is used in Web development and MVVM is most popular in WPF/Silverlight development.
However, sometimes the web architecute might have a mix of MVC and MVVM.
For example: you might use knockout.js and in this case you will have MVVM on your client side.
And your MVC's server side can also change. In the complex apps, nobody uses the pure Model. It might have a sense to use a ViewModel as a "Model" of MVC and your real Model basically will be a part of this VM. This gives you an extra abstraction layer.
The Controller is not replaced by a ViewModel in MVVM, because the ViewModel has a totally different functionality then a Controller. You still need a Controller, because without a Controller your Model, ViewModel and View will not do much... In MVVM you have a Controller too, the name MVVM is just missleading.
MVVMC is the correct name in my humble opinion.
As you can see the ViewModel is just an addition to the MVC pattern. It moves conversion-logic (for example convert object to a string) from the Controller to the ViewModel.
MVVMC, or perhaps MVC+, seems to be a viable approach for enterprise as well as rapid application development. While it is nice to separate the UI from business and interaction logic, the 'pure' MVVM pattern and most available examples work best on singular views.
Not sure about your designs, but most of my applications, however, contain pages and several (reusable) views and thus the ViewModels do need to interact to some degree. Using the page as controller would defeat the purpose of the MVVM altogether, so not using a "VM-C" approach for the underlying logic might result in .. well .. challenging constructs as the application matures. Even in VB-6 most of us probably stopped coding business logic into the Button event and started 'relaying' commands to a controller, right? I recently looked at many emerging framworks on that topic; my favorite clearly is the Magellan (at codeplex) approach. Happy coding!
http://en.wikipedia.org/wiki/Model_View_ViewModel#References
From a practical point of view, MVC (Model-View-Controller) is a pattern. However, MVC when used as ASP.net MVC, when combined with Entity Framework (EF) and the "power tools" is a very powerful, partially automated approach for bringing databases, tables, and columns to a web-page, for either full CRUD operations or R (Retrieve or Read) operations only. At least as I used MVVM, the View Models interacted with models that depended upon business objects, which were in turn "hand-made" and after a lot of effort, one was lucky to get models as good as what EF gives one "out-of-the-box". From a practical programming point of view, MVC seems a good choice because it gives one lots of utility out-of-box, but there is still a potential for bells-and-whistles to be added.
I used to think that MVC and MVVM are the same. Now because of the existence of Flux I can tell the difference:
In MVC, for each view in your app, you have a model and a controller, so I would call it view, view model, view controller. The pattern does not tell you how one view can communicate with another. Therefore, in different frameworks there are different implementations for that. For example there are implementations where controllers talk to each other whereas in other implementations there's another component that mediates between them. There are even implementations in which the view models communicate with each other, which is a break of the MVC pattern because the view model should only be accessed by the view controller.
In MVVM, you also have a view model for each component. The pattern does not specify how the heck the view should influence the view model, so usually most frameworks just include controller's functionality in the view model. However, MVVM does tell you that your view model's data should come from the model, which is the entire model that's not aware or custom to a specific view.
To demonstrate the difference, let's take Flux pattern. Flux pattern tells how different views in the app should communicate. Each view listens to a store and fires actions using the dispatcher. The dispatcher in turn tells all the stores about the action that was just made, and the stores update themselves. A store in Flux corresponds to the (general) model in MVVM. it's not custom to any specific view. So usually when people use React and Flux, each React component actually implements the MVVM pattern. When an action occurs, the view model calls the dispatcher, and finally it's getting updated according to the changes in the store, which is the model. You can't say that each component implements MVC because in MVC only the controller can update the view model. So MVVM can work with Flux together (MVVM handles the communication between the view and the view model, and Flux handles the communication between different views), whereas MVC can't work with Flux without breaking a key principle.
mvc is server-side and mvvm is client-side(browser) in web development.
most of the time javascript is used for mvvm in browser. there are many server side technologies for mvc.
Complementary to many of the responses given, I wanted to add some additional perspective from the Modern client-side web - or Rich Web Application point of view.
Indeed these days simple web sites and larger web applications are commonly built with many popular libraries such as Bootstrap. Built by Steve Sanderson, Knockout provides support for the MVVM pattern which mimics one of the most important behaviors in the pattern: data-binding through the View Model. With a little JavaScript, data and logic can be implemented that can then be added to page elements with simple data-bind HTML attributes, similar to using many of the features of Bootstrap. Together, these two libraries alone offer interactive content; and when combined with routing this approach can result in a simple-yet-powerful approach to building the Single Page Application.
Similarly, a Modern client-side framework such as Angular follows the MVC pattern by convention, but also adds a Service. Interestingly, it is touted as Model-View-Whatever (MVW). (See this post on Stack Overflow.)
Additionally, with the rise of Progressive web frameworks such as Angular 2, we're seeing a change in terminology and perhaps a new architectural pattern where Components comprise of a View or Template and interact with a Service - all of which can be contained in a Module; and a series of Modules makes up the application.

What are MVP and MVC and what is the difference?

Want to improve this post? Provide detailed answers to this question, including citations and an explanation of why your answer is correct. Answers without enough detail may be edited or deleted.
When looking beyond the RAD (drag-drop and configure) way of building user interfaces that many tools encourage you are likely to come across three design patterns called Model-View-Controller, Model-View-Presenter and Model-View-ViewModel. My question has three parts to it:
What issues do these patterns address?
How are they similar?
How are they different?
Model-View-Presenter
In MVP, the Presenter contains the UI business logic for the View. All invocations from the View delegate directly to the Presenter. The Presenter is also decoupled directly from the View and talks to it through an interface. This is to allow mocking of the View in a unit test. One common attribute of MVP is that there has to be a lot of two-way dispatching. For example, when someone clicks the "Save" button, the event handler delegates to the Presenter's "OnSave" method. Once the save is completed, the Presenter will then call back the View through its interface so that the View can display that the save has completed.
MVP tends to be a very natural pattern for achieving separated presentation in WebForms. The reason is that the View is always created first by the ASP.NET runtime. You can find out more about both variants.
Two primary variations
Passive View: The View is as dumb as possible and contains almost zero logic. A Presenter is a middle man that talks to the View and the Model. The View and Model are completely shielded from one another. The Model may raise events, but the Presenter subscribes to them for updating the View. In Passive View there is no direct data binding, instead, the View exposes setter properties that the Presenter uses to set the data. All state is managed in the Presenter and not the View.
Pro: maximum testability surface; clean separation of the View and Model
Con: more work (for example all the setter properties) as you are doing all the data binding yourself.
Supervising Controller: The Presenter handles user gestures. The View binds to the Model directly through data binding. In this case, it's the Presenter's job to pass off the Model to the View so that it can bind to it. The Presenter will also contain logic for gestures like pressing a button, navigation, etc.
Pro: by leveraging data binding the amount of code is reduced.
Con: there's a less testable surface (because of data binding), and there's less encapsulation in the View since it talks directly to the Model.
Model-View-Controller
In the MVC, the Controller is responsible for determining which View to display in response to any action including when the application loads. This differs from MVP where actions route through the View to the Presenter. In MVC, every action in the View correlates with a call to a Controller along with an action. In the web, each action involves a call to a URL on the other side of which there is a Controller who responds. Once that Controller has completed its processing, it will return the correct View. The sequence continues in that manner throughout the life of the application:
Action in the View
-> Call to Controller
-> Controller Logic
-> Controller returns the View.
One other big difference about MVC is that the View does not directly bind to the Model. The view simply renders and is completely stateless. In implementations of MVC, the View usually will not have any logic in the code behind. This is contrary to MVP where it is absolutely necessary because, if the View does not delegate to the Presenter, it will never get called.
Presentation Model
One other pattern to look at is the Presentation Model pattern. In this pattern, there is no Presenter. Instead, the View binds directly to a Presentation Model. The Presentation Model is a Model crafted specifically for the View. This means this Model can expose properties that one would never put on a domain model as it would be a violation of separation-of-concerns. In this case, the Presentation Model binds to the domain model and may subscribe to events coming from that Model. The View then subscribes to events coming from the Presentation Model and updates itself accordingly. The Presentation Model can expose commands which the view uses for invoking actions. The advantage of this approach is that you can essentially remove the code-behind altogether as the PM completely encapsulates all of the behavior for the view. This pattern is a very strong candidate for use in WPF applications and is also called Model-View-ViewModel.
There is a MSDN article about the Presentation Model and a section in the Composite Application Guidance for WPF (former Prism) about Separated Presentation Patterns
This is an oversimplification of the many variants of these design patterns, but this is how I like to think about the differences between the two.
MVC
MVP
I blogged about this a while back, quoting on Todd Snyder's excellent post on the difference between the two:
Here are the key differences between
the patterns:
MVP Pattern
View is more loosely coupled to the model. The presenter is
responsible for binding the model to
the view.
Easier to unit test because interaction with the view is through
an interface
Usually view to presenter map one to one. Complex views may have
multi presenters.
MVC Pattern
Controller are based on behaviors and can be shared across
views
Can be responsible for determining which view to display
It is the best explanation on the web I could find.
Here are illustrations which represent communication flow
MVP is not necessarily a scenario where the View is in charge (see Taligent's MVP for example).
I find it unfortunate that people are still preaching this as a pattern (View in charge) as opposed to an anti-pattern as it contradicts "It's just a view" (Pragmatic Programmer). "It's just a view" states that the final view shown to the user is a secondary concern of the application. Microsoft's MVP pattern renders re-use of Views much more difficult and conveniently excuses Microsoft's designer from encouraging bad practice.
To be perfectly frank, I think the underlying concerns of MVC hold true for any MVP implementation and the differences are almost entirely semantic. As long as you are following separation of concerns between the view (that displays the data), the controller (that initialises and controls user interaction) and the model (the underlying data and/or services)) then you are achieving the benefits of MVC. If you are achieving the benefits then who really cares whether your pattern is MVC, MVP or Supervising Controller? The only real pattern remains as MVC, the rest are just differing flavours of it.
Consider this highly exciting article that comprehensively lists a number of these differing implementations.
You may note that they're all basically doing the same thing but slightly differently.
I personally think MVP has only been recently re-introduced as a catchy term to either reduce arguments between semantic bigots who argue whether something is truly MVC or not or to justify Microsofts Rapid Application Development tools. Neither of these reasons in my books justify its existence as a separate design pattern.
MVP: the view is in charge.
The view, in most cases, creates its presenter. The presenter will interact with the model and manipulate the view through an interface. The view will sometimes interact with the presenter, usually through some interface. This comes down to implementation; do you want the view to call methods on the presenter or do you want the view to have events the presenter listens to? It boils down to this: The view knows about the presenter. The view delegates to the presenter.
MVC: the controller is in charge.
The controller is created or accessed based on some event/request. The controller then creates the appropriate view and interacts with the model to further configure the view. It boils down to: the controller creates and manages the view; the view is slave to the controller. The view does not know about the controller.
MVC (Model View Controller)
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)
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.
For more Reference
There are many answers to the question, but I felt there is a need for some really simple answer clearly comparing the two. Here's the discussion I made up when a user searches for a movie name in an MVP and MVC app:
User: Click click …
View: Who’s that? [MVP|MVC]
User: I just clicked on the search button …
View: Ok, hold on a sec … . [MVP|MVC]
( View calling the Presenter|Controller … ) [MVP|MVC]
View: Hey Presenter|Controller, a User has just clicked on the search button, what shall I do? [MVP|MVC]
Presenter|Controller: Hey View, is there any search term on that page? [MVP|MVC]
View: Yes,… here it is … “piano” [MVP|MVC]
Presenter|Controller: Thanks View,… meanwhile I’m looking up the search term on the Model, please show him/her a progress bar [MVP|MVC]
( Presenter|Controller is calling the Model … ) [MVP|MVC]
Presenter|Controller: Hey Model, Do you have any match for this search term?: “piano” [MVP|MVC]
Model: Hey Presenter|Controller, let me check … [MVP|MVC]
( Model is making a query to the movie database … ) [MVP|MVC]
( After a while ... )
-------------- This is where MVP and MVC start to diverge ---------------
Model: I found a list for you, Presenter, here it is in JSON “[{"name":"Piano Teacher","year":2001},{"name":"Piano","year":1993}]” [MVP]
Model: There is some result available, Controller. I have created a field variable in my instance and filled it with the result. It's name is "searchResultsList" [MVC]
(Presenter|Controller thanks Model and gets back to the View) [MVP|MVC]
Presenter: Thanks for waiting View, I found a list of matching results for you and arranged them in a presentable format: ["Piano Teacher 2001","Piano 1993"]. Please show it to the user in a vertical list. Also please hide the progress bar now [MVP]
Controller: Thanks for waiting View, I have asked Model about your search query. It says it has found a list of matching results and stored them in a variable named "searchResultsList" inside its instance. You can get it from there. Also please hide the progress bar now [MVC]
View: Thank you very much Presenter [MVP]
View: Thank you "Controller" [MVC]
(Now the View is questioning itself: How should I present the results I get from the Model to the user? Should the production year of the movie come first or last...? Should it be in a vertical or horizontal list? ...)
In case you're interested, I have been writing a series of articles dealing with app architectural patterns (MVC, MVP, MVVP, clean architecture, ...) accompanied by a Github repo here. Even though the sample is written for android, the underlying principles can be applied to any medium.
Model-View-Controller
MVC is a pattern for the architecture of a software application. It separate the application logic into three separate parts, promoting modularity and ease of collaboration and reuse. It also makes applications more flexible and welcoming to iterations.It separates an application into the following components:
Models for handling data and business logic
Controllers for handling the user interface and application
Views for handling graphical user interface objects and presentation
To make this a little more clear, let's imagine a simple shopping list app. All we want is a list of the name, quantity and price of each item we need to buy this week. Below we'll describe how we could implement some of this functionality using MVC.
Model-View-Presenter
The model is the data that will be displayed in the view (user interface).
The view is an interface that displays data (the model) and routes user commands (events) to the Presenter to act upon that data. The view usually has a reference to its Presenter.
The Presenter is the “middle-man” (played by the controller in MVC) and has references to both, view and model. Please note that the word “Model” is misleading. It should rather be business logic that retrieves or manipulates a Model. For instance: If you have a database storing User in a database table and your View wants to display a list of users, then the Presenter would have a reference to your database business logic (like a DAO) from where the Presenter will query a list of Users.
If you want to see a sample with simple implementation please check
this GitHub post
A concrete workflow of querying and displaying a list of users from a database could work like this:
What is the difference between MVC and MVP patterns?
MVC Pattern
Controller are based on behaviors and can be shared across views
Can be responsible for determining which view to display (Front Controller Pattern)
MVP Pattern
View is more loosely coupled to the model. The presenter is responsible for binding the model to the view.
Easier to unit test because interaction with the view is through an interface
Usually view to presenter map one to one. Complex views may have multi presenters.
MVP = Model-View-Presenter
MVC = Model-View-Controller
Both presentation patterns. They separate the dependencies between a Model (think Domain objects), your screen/web page (the View), and how your UI is supposed to behave (Presenter/Controller)
They are fairly similar in concept, folks initialize the Presenter/Controller differently depending on taste.
A great article on the differences is here. Most notable is that MVC pattern has the Model updating the View.
Also worth remembering is that there are different types of MVPs as well. Fowler has broken the pattern into two - Passive View and Supervising Controller.
When using Passive View, your View typically implement a fine-grained interface with properties mapping more or less directly to the underlaying UI widget. For instance, you might have a ICustomerView with properties like Name and Address.
Your implementation might look something like this:
public class CustomerView : ICustomerView
{
public string Name
{
get { return txtName.Text; }
set { txtName.Text = value; }
}
}
Your Presenter class will talk to the model and "map" it to the view. This approach is called the "Passive View". The benefit is that the view is easy to test, and it is easier to move between UI platforms (Web, Windows/XAML, etc.). The disadvantage is that you can't leverage things like databinding (which is really powerful in frameworks like WPF and Silverlight).
The second flavor of MVP is the Supervising Controller. In that case your View might have a property called Customer, which then again is databound to the UI widgets. You don't have to think about synchronizing and micro-manage the view, and the Supervising Controller can step in and help when needed, for instance with compled interaction logic.
The third "flavor" of MVP (or someone would perhaps call it a separate pattern) is the Presentation Model (or sometimes referred to Model-View-ViewModel). Compared to the MVP you "merge" the M and the P into one class. You have your customer object which your UI widgets is data bound to, but you also have additional UI-spesific fields like "IsButtonEnabled", or "IsReadOnly", etc.
I think the best resource I've found to UI architecture is the series of blog posts done by Jeremy Miller over at The Build Your Own CAB Series Table of Contents. He covered all the flavors of MVP and showed C# code to implement them.
I have also blogged about the Model-View-ViewModel pattern in the context of Silverlight over at YouCard Re-visited: Implementing the ViewModel pattern.
Both of these frameworks aim to seperate concerns - for instance, interaction with a data source (model), application logic (or turning this data into useful information) (Controller/Presenter) and display code (View). In some cases the model can also be used to turn a data source into a higher level abstraction as well. A good example of this is the MVC Storefront project.
There is a discussion here regarding the differences between MVC vs MVP.
The distinction made is that in an MVC application traditionally has the view and the controller interact with the model, but not with each other.
MVP designs have the Presenter access the model and interact with the view.
Having said that, ASP.NET MVC is by these definitions an MVP framework because the Controller accesses the Model to populate the View which is meant to have no logic (just displays the variables provided by the Controller).
To perhaps get an idea of the ASP.NET MVC distinction from MVP, check out this MIX presentation by Scott Hanselman.
Both are patterns trying to separate presentation and business logic, decoupling business logic from UI aspects
Architecturally, MVP is Page Controller based approach where MVC is Front Controller based approach.
That means that in MVP standard web form page life cycle is just enhanced by extracting the business logic from code behind. In other words, page is the one servicing http request. In other words, MVP IMHO is web form evolutionary type of enhancement.
MVC on other hand changes completely the game because the request gets intercepted by controller class before page is loaded, the business logic is executed there and then at the end result of controller processing the data just dumped to the page ("view")
In that sense, MVC looks (at least to me) a lot to Supervising Controller flavor of MVP enhanced with routing engine
Both of them enable TDD and have downsides and upsides.
Decision on how to choose one of them IMHO should be based on how much time one invested in ASP NET web form type of web development.
If one would consider himself good in web forms, I would suggest MVP.
If one would feel not so comfortable in things such as page life cycle etc MVC could be a way to go here.
Here's yet another blog post link giving a little bit more details on this topic
http://blog.vuscode.com/malovicn/archive/2007/12/18/model-view-presenter-mvp-vs-model-view-controller-mvc.aspx
I have used both MVP and MVC and although we as developers tend to focus on the technical differences of both patterns the point for MVP in IMHO is much more related to ease of adoption than anything else.
If I’m working in a team that already as a good background on web forms development style it’s far easier to introduce MVP than MVC. I would say that MVP in this scenario is a quick win.
My experience tells me that moving a team from web forms to MVP and then from MVP to MVC is relatively easy; moving from web forms to MVC is more difficult.
I leave here a link to a series of articles a friend of mine has published about MVP and MVC.
http://www.qsoft.be/post/Building-the-MVP-StoreFront-Gutthrie-style.aspx
In MVP the view draws data from the presenter which draws and prepares/normalizes data from the model while in MVC the controller draws data from the model and set, by push in the view.
In MVP you can have a single view working with multiple types of presenters and a single presenter working with different multiple views.
MVP usually uses some sort of a binding framework, such as Microsoft WPF binding framework or various binding frameworks for HTML5 and Java.
In those frameworks, the UI/HTML5/XAML, is aware of what property of the presenter each UI element displays, so when you bind a view to a presenter, the view looks for the properties and knows how to draw data from them and how to set them when a value is changed in the UI by the user.
So, if for example, the model is a car, then the presenter is some sort of a car presenter, exposes the car properties (year, maker, seats, etc.) to the view. The view knows that the text field called 'car maker' needs to display the presenter Maker property.
You can then bind to the view many different types of presenter, all must have Maker property - it can be of a plane, train or what ever , the view doesn't care. The view draws data from the presenter - no matter which - as long as it implements an agreed interface.
This binding framework, if you strip it down, it's actually the controller :-)
And so, you can look on MVP as an evolution of MVC.
MVC is great, but the problem is that usually its controller per view. Controller A knows how to set fields of View A. If now, you want View A to display data of model B, you need Controller A to know model B, or you need Controller A to receive an object with an interface - which is like MVP only without the bindings, or you need to rewrite the UI set code in Controller B.
Conclusion - MVP and MVC are both decouple of UI patterns, but MVP usually uses a bindings framework which is MVC underneath. THUS MVP is at a higher architectural level than MVC and a wrapper pattern above of MVC.
My humble short view: MVP is for large scales, and MVC for tiny scales. With MVC, I sometime feel the V and the C may be seen a two sides of a single indivisible component rather directly bound to M, and one inevitably falls to this when going down‑to shorter scales, like UI controls and base widgets. At this level of granularity, MVP makes little sense. When one on the contrary go to larger scales, proper interface becomes more important, the same with unambiguous assignment of responsibilities, and here comes MVP.
On the other hand, this scale rule of a thumb, may weight very little when the platform characteristics favours some kind of relations between the components, like with the web, where it seems to be easier to implement MVC, more than MVP.
I think this image by Erwin Vandervalk (and the accompanying article) is the best explanation of MVC, MVP, and MVVM, their similarities, and their differences. The article does not show up in search engine results for queries on "MVC, MVP, and MVVM" because the title of the article does not contain the words "MVC" and "MVP"; but it is the best explanation, I think.
(The article also matches what Uncle Bob Martin said in his one of his talks: that MVC was originally designed for the small UI components, not for the architecture of the system)
There are many versions of MVC, this answer is about the original MVC in Smalltalk. In brief, it is
This talk droidcon NYC 2017 - Clean app design with Architecture Components clarifies it
MVC (Model-View-Controller)
In MVC, the Controller is the one in charge! The Controller is triggered or accessed based on some events/requests then, manages the Views.
Views in MVC are virtually stateless, the Controller is responsible for choosing which View to show.
E.g.: When the user clicks on the “Show MyProfile” button, the Controller is triggered. It communicates with the Model to get the appropriate data. Then, it shows a new View that resembles the profile page. The Controller may take the data from the Model and feed it directly to the View -as proposed in the above diagram- or let the View fetch the data from the Model itself.
MVP (Model-View-Presenter)
In MVP, the View is the one in charge! each View calls its Presenter or has some events that the Presenter listens to.
Views in MVP don’t implement any logic, the Presenter is responsible for implementing all the logic and communicates with the View using some sort of interface.
E.g.: When the user clicks the “Save” button, the event handler in the View delegates to the Presenter’s “OnSave” method. The Presenter will do the required logic and any needed communication with the Model then, calls back the View through its interface so that the View can display that the save has been completed.
MVC vs. MVP
MVC doesn’t put the View in charge, Views act as slaves that the Controller can manage and direct.
In MVC, Views are stateless contrary to Views in MVP where they are stateful and can change over time.
In MVP, Views have no logic and we should keep them dumb as possible. On the other hand, Views in MVC may have some sort of logic.
In MVP, the Presenter is decoupled from the View and talks to it through an interface. This allows mocking the View in unit tests.
In MVP, Views are completely isolated from the Model. However, in MVC, Views can communicate with the Model to keep it up with the most
up-to-date data.
The simplest answer is how the view interacts with the model. In MVP the view is updated by the presenter, which acts as as intermediary between the view and the model. The presenter takes the input from the view, which retrieves the data from the model and then performs any business logic required and then updates the view. In MVC the model updates the view directly rather than going back through the controller.
There is this nice video from Uncle Bob where he briefly explains MVC & MVP at the end.
IMO, MVP is an improved version of MVC where you basically separate the concern of what you're gonna show (the data) from how you're gonna show (the view). The presenter includes kinda the business logic of your UI, implicitly imposes what data should be presented and gives you a list of dumb view models. And when the time comes to show the data, you simply plug your view (probably includes the same id's) into your adapter and set the relevant view fields using those view models with a minimum amount of code being introduced (just using setters). Its main benefit is you can test your UI business logic against many/various views like showing items in a horizontal list or vertical list.
In MVC, we talk through interfaces (boundaries) to glue different layers. A controller is a plug-in to our architecture but it has no such a restriction to impose what to show. In that sense, MVP is kind of an MVC with a concept of views being pluggable to the controller over adapters.
I hope this helps better.
You forgot about Action-Domain-Responder (ADR).
As explained in some graphics above, there's a direct relation/link between the Model and the View in MVC.
An action is performed on the Controller, which will execute an action on the Model. That action in the Model, will trigger a reaction in the View.
The View, is always updated when the Model's state changes.
Some people keep forgetting, that MVC was created in the late 70", and that the Web was only created in late 80"/early 90".
MVC wasn't originally created for the Web, but for Desktop applications instead, where the Controller, Model and View would co-exist together.
Because we use web frameworks (eg:. Laravel) that still use the same naming conventions (model-view-controller), we tend to think that it must be MVC, but it's actually something else.
Instead, have a look at Action-Domain-Responder.
In ADR, the Controller gets an Action, which will perform an operation in the Model/Domain. So far, the same.
The difference is, it then collects that operation's response/data, and pass it to a Responder (eg:. view()) for rendering.
When a new action is requested on the same component, the Controller is called again, and the cycle repeats itself.
In ADR, there's no connection between the Model/Domain and the View (Reponser's response).
Note: Wikipedia states that "Each ADR action, however, is represented by separate classes or closures.". This is not necessarily true. Several Actions can be in the same Controller, and the pattern is still the same.
mvc adr model-view-controller action-domain-responder
In a few words,
In MVC, View has the UI part, which calls the controller which in turn calls the model & model in turn fires events back to view.
In MVP, View contains UI and calls the presenter for implementation part. The presenter calls the view directly for updates to the UI part.
Model which contains business logic is called by the presenter and no interaction whatsoever with the view. So here presenter does most of the work :)
MVP
MVP stands for Model - View- Presenter. This came to a picture in early 2007 where Microsoft introduced Smart Client windows applications.
A presenter is acting as a supervisory role in MVP which binding View events and business logic from models.
View event binding will be implemented in the Presenter from a view interface.
The view is the initiator for user inputs and then delegates the events to the Presenter and the presenter handles event bindings and gets data from models.
Pros:
The view is having only UI not any logics
High level of testability
Cons:
Bit complex and more work when implementing event bindings
MVC
MVC stands for Model-View-Controller. Controller is responsible for creating models and rendering views with binding models.
Controller is the initiator and it decides which view to render.
Pros:
Emphasis on Single Responsibility Principle
High level of testability
Cons:
Sometimes too much workload for Controllers, if try to render multiple views in same controller.

Resources