Should models or views generate strings for humans? - model-view-controller

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.

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

MVC 3 - using reflection to choose a partial view - abuse?

I think I'm finally starting to get MVC 3, but if someone can validate this approach I'd feel better about it.
I have a website, let's say, and I have models for NormalPage and EventPage. EventPage has an EventDate, but that's the only difference, and let's just say that EventPage inherits from NormalPage if that makes life easier.
Two views handle these two (slightly) different models, one just showing the page, and the other displaying the date and showing a registration form. They have different designs, so different views are in order.
All the tutorials will say "yup, now write two Controllers: Events and Pages". That seems silly - both are just passing the model to a (appropriate) view. I can use a single "Page" controller and choose the appropriate view using reflection, right? typeof(Model), once I've pulled the data from the database, can tell me whether or not I should pull the Event view or the Page view.
Is that dumb, or asking for trouble, or misusing the framework? Thanks.
What do you intend to do with reflection? You don't need to do anything like that to return views dynamically. From any controller action, you can return View("EventView", eventModel) or View("NormalView", normalModel) and it will return that view.
On a different note, I'm not sure what tutorials suggested that it's typical to have one view per controller but it's not. It's typical to have several views and actions in one controller.

what is the correct way of using Models with Partial Views in ASP.NET MVC2?

I'm pretty new to MVC, but now feel pretty comfortable with the pattern, particularly finding ViewModels to be an excellent bridge between controller and view.
However, I'm now going to have to use Partial Views, and am a little confused.
Requirement
Ok, in the Wire Frames we have many different pages, but which share a common "grid".
The Grid will be a Partial View and will always render/consume/manipulate the same TYPE of data.
Questions
So, the main Views that include the partial view will have different Models... so how do I handle the models from within the partial view.
Should all Models for Views that use that certain Partial View have a nested model for the partial view as a property?
What the best practice here?
cool, cheers
I find that when I am putting together a Partial, it helps immensely if I consider what the Model for that Partial will be. I almost always find that if I take a moment to consider that, the reusability of the partial increases a lot.
A Partial should usually use some natural sub-set or variation of the data in the Model of the whole View. When your creation of a Partial starts with that in mind, having to think too much about "what model should my partial use" is often an indication that perhaps you should be creating a different partial instead of trying to re-use one.
If you are having to re-construct a new model for a Partial, I think the problem may be that your whole View's model isn't covering everything you need.
With that said, though; there are many times where I have a Partial that uses a Model that seems to be separate from the whole View's Model. But most of the time those models are new/empty objects - not ones that need to be instantiated and have properties set, etc. (this usually happens for Partials that are being used in Ajax-related updates)
Note that MVC2 has something for this too, though; Html.RenderAction() lets you call a whole new Action (which would have its own Model) and render it within the current View. I try to avoid needing to use it, myself, actually... but it would feel better, to me, than trying to 'build' some new Model for a Partial, or adding in unnatural information in the current ViewModel.

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.

Resources