What's the difference between a ViewModel and Controller? - ruby-on-rails

What are the responsibilities of one vs the other?
What kind of logic should go in one vs the other?
Which one hits services and databases?
How do I decide if my code should go in the viewmodel or the controller?
For the record, I am using ASP MVC, but since the question is architectural, I do not believe it matters what language or framework I am using. I'm inviting all MVC to respond

The ViewModel is a Pattern used to handle the presentation logic and state of the View and the controller is one of the fundamentals parts of any MVC framework, it responds to any http request and orchestrates all the subsequent actions until the http response.
The ViewModel Pattern: More info
In the ViewModel pattern, the UI and
any UI logic are encapsulated in a
View. The View observes a ViewModel
which encapsulates presentation logic
and state. The ViewModel in turn
interacts with the Model and acts as
an intermediary between it and the
View.
View <-> ViewModel <-> Model
The Controllers (Comes from the Front Controller Pattern): More Info
It "provides a centralized entry point
for handling requests."
HTTP Request -> Controller -> (Model,View)
--Plain Differences:--
While the ViewModel is an optional
pattern the Controller is a must, if
you are going the MVC way.
The ViewModel encapsulates
presentation logic and state, The
Controller orchestrates all the
Application Flow.

The ViewModel can be on the client side as well as server side.
Wherever it may be, the sole purpose of viewmodel is to play the
presentation data.
In MVC architecture Viewmodel is not mandatory but with out controller the request from the client cannot be processed.
Controller can be visualised as the main interface between client and server to get any response from the server. It processes the client request, fetches data from repository and then prepares the view data. Viewmodel can be visualised as view data processor/presenter thus an interface to manage the view more eloquently.
In the overall context of a web application we can say the controller is the application request handler whereas viewmodel is only the UI handler.

The Model-View-Controller (MVC) is an architectural design pattern which exists, primarily, to separate business logic from the presentation. Basically, you don't want your back-end touching your front. It typically looks like this:
The reasons for doing this is because, by separating the back-end and the front, you don't tie your user-interface directly to your data/work. This allows you to put new interfaces onto your business logic without affecting said logic. In addition, it also improves the ease of testing.
A simple example of where MVC comes in handy - let's say you have an application that manages your company's finances. Now, if you are correctly using MVC, you can have a front end that sits at some financier's desk and lets him handle transactions, manage the finances, etc. BUT, because the business logic is separate, you can also provide a front-end to your CEO's Blackberry that lets him see the current status of the business. Because the two front-ends are different, they can do different things while still providing (different types of) access to the data.
EDIT:
Since you updated your question a bit, I'll update my answer. There is no perfect science to the separation of MVC. There are some good rules of thumb, however. For example, if you are talking about GUI components, that is probably a view. (Are you talking about look and feel, usability, etc.) If you are talking about data and the "business" side of the house (databases, logic, etc), you are probably referring to a model. And, anything that controls the interaction between the two is most likely a controller.
In addition, it should be noted that, while Views and Models are typically "physically" separated, a controller can exist with a view when it makes sense.
You are correct when you say the framework (or even language) for MVC doesn't matter. The pattern itself is language agnostic and really describes a way to architect your system.
Hope that helps!

I think there's some value to learning received doctrine. But there is also value in understanding how the doctrine came to be the way it is.
Trygve Reenskaug is widely credited with inventing MVC. N. Alex Rupp's article Beyond MVC: A new look at the servelet architecture includes a History of MVC. In a section on Reenskaug's 1978 work at Xerox Palo Alto Research Center, there's a link to his paper Thing-Model-View-Editor: an Example from a planningsystem. There the pieces are described like this.
Thing
Something that is of interest to the user. It could be concrete, like a house or an integrated
circuit. It could be abstract, like a new idea or opinions about a paper. It could be a whole,
like a computer, or a part, like a circuit element.
Model
A Model is an active representation of an abstraction in the form of data in a computing
system
View
To any given Model there is attached one or more Views, each View being capable of
showing one or more pictorial representations of the Model on the screen and on hardcopy. A
View is also able to perform such operations upon the Model that is reasonabely associated
with that View.
Editor
An Editor is an interface between a user and one or more views. It provides the user with a suitable command system, for example in the form of menus that may change dynamically
according to the current context. It provides the Views with the necessary coordination and
command messages.
Rupp identifies Reenskaug's Editor as a Controller or Tool.
MVC Triads emerged in SmallTalk-80. The model was an abstraction of the real-world concept, the view was its visual representation, and the controller was the buttons and slider bars that allowed the user to interact with it (thereby "controlling" the view). All pieces in the triad were interconnected and could communicate with the other two pieces, so there was no layering or abstraction involved. Since then, Reenskaug has "preferred to use the term Tool rather then Controller." According to his notes, these are the terms he has used in later implementations

Some logic and model should be invoked to generate some data (structured or semi-structured). From this data the returned page/JSON/etc. is created, typically with only rudimentary outlining logic.
The first part (creating the data) is done by the controller (via the model usually). The second part - by the View. The ViewModel is the data structure being passed between controller and view, and usually contains only accessors.

Model represents your data and how it's manipulated. Thus, model touches the DB.
View is your UI.
Controler is the glue between them.

MVC stands for Model, View, Controller.
Model = Data (Database tables)
View = HTML, CSS, JavaScript, etc
Controller = Main logic, a contract between Model & View.
In simple and graspable terms,
MVC allows you to develop your applications in a way that your business data and presentation data are separated. With this, a developer and designer can work independently on a MVC app without their work clashing. MVC makes your app avail OOP too.

Related

Having MVC controllers light and models heavy

I have heard that the controller should be kept light and models heavy.
I am somewhat confused about the best practice on what should be kept in the controller and what should be kept in the model.
In our organization, we use Entity Framework where and put the tables there.
For the controller, we use LINQ and then send the info over to the view.
Kind of confused on what code should be in the Controller and in the Model.
DisclaimerThe whole topic is a giant mess. Especially when it comes to Web MVC. For all practical purposes it is impossible to use classical MVC pattern for web, because the view should be observing model. Theoretically you could implement something like that with WebSockets, but keeping a persistent model for each user is not a realistic solution.
Here is what you must know about MVC
The most important idea in both classical MVC and MVC-inspired patterns Separation of Concerns. It divides the application in two major layers:
Presentation layer
Governs the user interface. It deals with both creation of the interface and reacts to the user's manipulation of this interface. This interface might be GUI for a desktop application or HTML web page, but it also can be REST API or receiver-responder on a Mars rover. This is why a web application can implement MVC pattern in both frontend and backend.
The mandatory parts are views and controllers, but, in context of web, fully realized views usually also use multiple templates to create the interface.
Model layer
This is where all the business rules and logic lives. The M in MVC is not a single entity. Instead it is a layer, which contains different structures. Some of those structures are also responsible for interaction with storage.
What are the responsibilities of controllers ?
Controllers are part of presentation layer, which deals with user input. In context of web-based implementations, you will usually have 1:1 relationship between views and controllers, where controller receives the requests from browser and, based on the content of said requests, alters the state of model layer and view.
If you are using classical MVC or Model2 MVC, then that is the extent of controllers responsibilities.
In MVP and MVVM patterns, where you have a passive view, controller-like structures are responsible for acquiring information from model layer and passing it on to the current view instance. This post might provide some additional details on the MVC-inspired patterns.
But the controller is in no way responsible for any form of business logic. If it was, it would mean, that you have a leaking abstraction, because the structures of presentation layer would be doing work, which should be in the model layer.
Usually the controllers will the be simplest structures in you application.
What about the model ?
As mentioned before, model is a layer, which encompasses all of the domain business logic and related functionality. This layer , just like presentation layer, is made up from multiple groups of structures:
Domain Objects[1]
These structures are usually what people mean, when talking about "models". They are also known as model objects or business objects. This is where most of domain business logic ends up.
Data Storage Structures
This group would contain all of the classes, which abstract the interaction with storage (SQL databases, caching systems, noSQL, remote SOAP or REST APIs). They will usually implement some variation of data mapper or repository pattern , but you could be using some other solutions too, like unit of work. The implementation details are not so important. What is important is that they let you store data from and retrieve information into your domain objects.
Services
Or you could call the "components". There are high level abstractions in your model layer, which facilitate the interaction between domain objects and storage structures. The usually represent large chunks of model layer, like "recognition service", "mailers", "article management", and will provide the interface for presentation layer to interact with.
That's something of a religious debate.
Some like as little as possible code in their controller and other as little as possible in their model.
Do what feels natural to you in the project, but be consistent within it.
All else is dogma you can pick an example either way and make a case.
Model is the core of your application. It is best to think of models as of your business entities. Do you want to create a view of an invoice? Then Invoice be your model, it represents the underlying object.
Controller is just a way to handle requests from a client, retrieving the data from database (or updating them) and flushing out the responses.
Your thoughts about the application design should be model-centric, that's the important part.
In simple terms, Model represents the underlying data that your application will be using. It is to be designed in a way that it can be used across different applications.
For example, A model to represent News data can be used by console commands, Web service etc.
It is in model where you will have ur business logic defined, independent of the view.
Controller can be thought of as glue that binds Model and View together. They deal directly with client requests and accordingly interact with views and models.
In a well designed application, you data structure and business logic will be designed in a
Model, making it "heavy". While Controller will just interlink your model and view with the client requests, making it "light".
In the classic Model-View-Controller MVC pattern, your Model is essentially a "headless" application, with no UI and is completely UI-agnostics. It offers an API that is the functional core of the application.
The View is the user interface, however you choose to define it (web page? elevator control panel? something else?). A given application might have 1 view or it might have many views.
The Controller (or Controllers — like Views, you might have one to many Controllers for a given application) relays and transforms events, notifications and data between View and Model so as to preclude the Model from needing to know anything that is View-specific.
The idea is to isolate the core application (the Model) from the user interface (the View). From that some things follow:
The View is aware of and communicates with both Controller and Model (you're unlikely to try to wire up the View to another Model) and expected for the Controller to be aware of both View and Model.
The Controller is aware of and communicates with both View and Model.
The Model knows nothing of Controller or View.
Code that performs business logic should be in the Model, not in the Controller.
I'm no MVC expert, but try and concentrate on the fact that the controller should use the input from the user to direct them to the correct view.
I don't know if NerdDinner is an ideal example, but you can see Scott Hanselman et al does a little bit of data access from his EF context but pushes most of the other logic to service classes or helpers on the model.
I don't know if I agree with the 'models heavy' part, as I don't use the models as 'business objects'. If I really need a lot of 'business' logic, I will typically create that in a separate 'Domain' layer and may even have a separate Data Access layer on top of this. But for a lot of simple (see: non-enterprise) projects, this is overkill in my experience.

MVVM ViewModel vs. MVC ViewModel

ViewModel is a term that is used in both MVVM (Model-View-ViewModel) and the recommended implementation for ASP.NET MVC. Researching "ViewModel" can be confusing given that each pattern uses the same term.
What are the main differences between the MVC ViewModel and MVVM ViewModel? For example, I believe the MVVM ViewModel is more rich, given the lack of a Controller. Is this true?
A rather challenging question to answer succinctly, but I'll attempt it. (Bear in mind that the answers to these kinds of questions are still the subject of debate amongst developers.)
In MVC, the ViewModel provides all the information necessary for a View to be rendered. The data it contains is created using data defined in the Model. The View reads the ViewModel and renders the output. Input from the View is passed to the Controller, which manipulates the Model, constructs an appropriate ViewModel, and passes this to the View for rendering.
In MVVM, the ViewModel serves the same function as it does in MVC, but it also replaces part of the MVC Controller by providing commands which allow the View to manipulate the Model. WPF databinding manages the updating of the View according to changes in the ViewModel (and this effectively replaces the remaining function of the MVC Controller).
It's been a while since I played UI Design Patterns Bingo.. however let me take a stab at this..
MVVM is just something that MS has come up with... because it helps you to get the most out of WPF. You combine the state and behavior of the view into a class (a presentation model) that is easily testable + then you use data-binding to get the data into any view.
This link has a brief of the evolution of MVVM. Combine this with Fowler's "GUI Architectures" series, and you should be on your way.
Update: Didn't know there was something called MVC-VM. Apparently a brainchild of the ASP.NET MVC crowd. Looks and sounds similar to MVVM (except tuned for ASP.NET MVC); the only difference is that it places a restriction that there is 1:1 mapping between VM and View. I'd have guessed 1:N, but everything else matches.
I know this is a (way) old question, but I've been pointed to it as an example of using "View Model" in the context of MVC. I argue that this is incorrect and can lead to confusion by people who are new to either/or/both patterns. Whoever is doing it--stahp. Here's why (and it's even an answer to the original question in a roundabout way).
An example of when this happens can be seen in this question. The user is trying to use a View Model that implements INotifyPropertyChanged in an ASP.NET MVC application, thus mashing together desktop and stateless web application design in an architectural fail and heartbreak.
To put it simply, there is no "View Model" in the MVC pattern. There is, however, a functional equivalent, and that's the Controller. Just to be clear about the parts and their purpouses,
MVVM (desktop applications):
Model - Strongly typed object that holds data to be passed between the View and View Model
View - The UI viewed by the user and through which the user interacts with the system
View Model - Interprets user actions (e.g., via ICommand), performs them, updates application state
MVC (web applications):
Model - Strongly typed* object that holds data to be passed between the View and View Model
View - A UI generator that combines the Model, code and HTML to render a webpage
Controller - Accepts user requests, interprets them, updates application state and uses a View to convert this state into an HTML webpage
The Model is practically the same in both patterns. Desktop models may implement update event notifications, web Models may be dynamic (i.e., not strongly typed), and both may or may not include validation methods or metadata.
The View in the desktop is what the user sees. In the web, it is a generator that outputs HTML for browsers to display on the client side. It must interpret user interaction on the desktop, but on the web that is handled by client side javascript, the browser, and the requests that are sent back to the server.
The View Model/Controller are roughly functionally equivalent, but differ greatly in how they are implemented and how they operate. In the View Model, user interaction with the application is transferred to View Models via ICommands, routed events, and other methods (many MVVM frameworks provide different ways to hook View Models to the UI and other parts of the application). In a Controller, a request comes in with all information needed for the Controller to return a result to the user (assuming it's a 200 OK request). The Controller must perform whatever work is necessary to create the state (aka Model) needed for the HTML generator (the View) to create the response. Design-wise, the Controller sits above the View and Model knowing and controlling both, whereas the ViewModel sits next to the View, passing the Model (and other information) between them.
What really seems to confuse some people is that there are client side MVVM frameworks that you can mix into your MVC application. These exist solely in javascript in the user's browser, and have nothing to do with whatever particular pattern you're following on the server side. You can run a classic ASP website that uses MVVM on the client side. Hell, you can run static HTML pages that use MVVM on the client side. They are that separate.
These javascript MVVM frameworks typically follow a similar pattern to the desktop MVVM pattern described above, but adjusted to work more in tune with the nature of the HTML DOM and javascript. For example, there is no extensive binding system woven into the DOM, and javascript has a very limited type system, so matching up templates to models is much different than in WPF. They also typically work disconnected from the server, and when they need to interact, prefer AJAX calls rather than POSTing the page back to the Controller (AJAX calls typically are handled by WebAPI Controllers in ASP.NET MVC).
So, to summarize, there really isn't a View Model in MVC. The Controller is the rough equivalent, but is very different in how it receives user input, interprets it, and returns a result to the user. Using the term "View Model" to refer to anything in MVC can only lead to confusion, and therefore should be avoided. Use the proper terms for the proper parts of the pattern. It may seem pedantic, but it should help keep things clear and be less confusing to people who are new to both patterns.

what is the difference between a view model and a data transfer object?

I'm basing this question on Fowler PoEAA. Given your familiarity with this text, aren't the ViewModels used in ASP.NET MVC the same as DTOs? Why or why not? Thank you.
They serve a similar purpose (encapsulating data for another layer of the application) but they do it differently and for different reasons.
The purpose of a DTO is to reduce the number of calls between tiers of an application, especially when those calls are expensive (e.g. distributed systems). DTOs are almost always trivially serializable, and almost never contain any behaviour.
For example, you're developing an e-Commerce site. CreateCustomer and AddCustomerAddress are separate operations at the database level, but you might for performance reasons want to aggregate their data into a NewCustomerWithAddressDto so that your client only needs to make one round-trip to the server, and doesn't need to care that the server might be doing a bunch of different things with the parcel of data.
The term "ViewModel" means slightly different things in different flavours of MV*, but its purpose is mainly separation of concerns. Your Model is frequently optimised for some purpose other than presentation, and it's the responsibility of the ViewModel to decouple your View from the Model's implementation details. Additionally, most MV* patterns advise making your Views as "dumb" as possible, and so the ViewModel sometimes takes responsibility for presentation logic.
For example, in the same e-Commerce application, your CustomerModel is the wrong "shape" for presentation on your "New Customer" View. For starters, your View has two form fields for your user to enter and confirm their password, and your CustomerModel doesn't contain a password field at all! Your NewCustomerViewModel will contain those fields and might, depending on your flavour of MV*, be responsible for some presentation logic (e.g. to show/hide parts of the view) and basic validation (e.g. ensuring that both password fields match).
The purpose is different:
DTO's are used to transfer data
ViewModels are used to show data to an end user.
So normally ViewModels contain the presentation data, witch is in a lot of cases similar to what is in a DTO, but with some differences. Think of representation of enums, localization, currency, date formats, ... . This is because normally there should be no logic in your view.
DTOs in MVVM and MVP are usually Very Dumb Objects and are basically just a bunch of property setters and getters. ViewModels on the other hand can have some behaviour.
A practical positive side effect of having DTOs is allow easier serialization. If you have a rather complex object in, say C#, you will often find yourself having to selectively turn things off that you don't want serialized. This can get rather ugly and DTOs simplify this process.
A View Model and a Data Transfer object has similarities and differences.
Similar:
Transfer data in a record (object instance, perhaps serialized) to a receiver, whether a view or a service
Difference:
A View Model is intended to be sent to a View, where it will be displayed, with formatting.
A View Model also sends back data to a controller.
A DTO is usually not intended for presentation. It is intended to send raw data.
Both serve the same purpose to model data coming to and from the backend.
View Models model data hitting the backend from a front end visual system (forms, user inputs, etc) and vice versa model data to be sent to the front end for the same purpose to fulfill some visual requirement.
Data Transfer Objects model data hitting the backend from some client system (background api's, data that still needs to be worked on, a clients background services, etc) and vice versa model data to be sent to the client system. Even though the client system may have visual elements, the DTO call itself is used for a non visual use case.
The technical differences between the two arise from the semantic and contextual meaning of the two as mentioned above, such as view models possibly having more behaviour.
I always thought DTO's were supposed to be almost like for like your Entities and ViewModels were containers for those DTO's when presenting to the View.
In that instance you would create 'pseudo' DTO's that combine 2 or more other DTO's together to pass data in one 'model' to a method or API etc.
I never came up with a naming convention for those 'pseudo' DTO's though, so just ended up suffixing them with "DTO", but put them in the models Folder along with the view models 🤷‍♂️
The ViewModel may have presentation logic based on; the current user's permissions, the display type, the data in the DTO's etc.
I've always tried to keep my views as 'dumb' as possible with as little as possible code in them, and just bound the view to the properties in the view model.

Simple Elegant pattern to separate Data Access, Business logic and presentation

I need a simple pattern to do the above.
Few things to note:
1) I have a class that I am obliged to use that does the actual data retrieving and it return DataTable
2) I am not concerned with the generic interfaces that support all possible database types, we are sticking with one database type.
3) How do I elegantly trap the error and inform the user that error occured.
4) Do not offer me to learn MVC - it is not an option right now.
I am interested in the actual pattern design.
You want to use the MVC pattern to separate business logic from presentation (note that I am NOT talking about the ASP.NET MVC Framework) and the DAO pattern to separate business logic from data access.
Your class that returns a DataTable becomes part of your model. You write a layer (a DAO for each domain object) that takes your DataTable and translates it into your various domain objects. Your UI shouldn't contain any logic that does more than presenting output to the user; anything that is actual logic for retrieving data from your model is handled in a controller layer, that gets the data the user is requesting from the model and sends it to the appropriate view to present it to the user.
Exceptions should be handled at layer boundaries; either catch and do something about it (which might just be to log it and send the user to an error page), or wrap in a higher-level exception as appropriate.
Do not offer me to learn MVC - it is not an option right now.
You can do a simple MVC or MVP pattern without using the ASP MVC Framework. It is pretty simple to introduce. Here is a pretty simple example MVP Example
There are a number of patterns that approach what you describe. I would recommend getting a copy of Martin Fowler's excellent book Patterns of Enterprise Architecture specifically Chapter 14. Web Presentation Patterns. You will find that any serious attempt to separate the presentation, domain (business logic), and data source will lead you to one of many variations of the same theme.
MVC, MVP, visual proxy, etc all break down to three layers what differs is the responsibilities of each layer and how layers communicate with each other.
For instance, the Passive View pattern basically strips the UI layer of anything not directly related to presentation. The typicall example being a field you want to highlight if a certain condition is true. In a Passive View the form would only only contain the logic to determine the whether the field should be highlighted. The business rule that trigger's this state would be in a presenter/controller layer which does not directly depend on the actual view.
As far as the data source layer, the main benefit isn't being able to switch databases at the drop of a hat. The main benefit is that changes to the database schema only affect the data source layer and don't extend into the rest of the application. If your stuck with datasets a good approach is the Table Data Gateway pattern.

Where are the Business Rules in MVC

Now that everyone is talking about MVC, I notice that the business rules are not being addressed. In the old days of the 3-tier architecture, The business rules were in the middle layer. Where do they fall in the new MVC?
The reason you never see MVC address "Business Rules" is that MVC by and large is a presentation pattern. It's focused on how to structure your application. The Model, for example, can be thought of as a presentation model. The model of your application, which the view then renders.
However, in order to create the presentation model, you generally need to go to your domain models where all your business logic lives. At that point, MVC doesn't dictate where that code physically live. Is it on another tier? MVC doesn't care.
At first brush, I'd say they belong in the model. The MVC Entry on Wikipedia seems to agree: "In MVC, the model represents the information (the data) of the application and the business rules used to manipulate the data".
After all, by 'Business rules' we mean the functional algorithms and logic that encode the domain that your application is involved with, as opposed to input/output related logic. These core business-related logic does not - or should not- change based upon what is being displayed to the user (which is the domain of the View) or the user input (which is primarily received by the Controller).
In my experience, asking this sort of question has been very revealing during the software development process: we found a large number of things that were considered 'business rules' by some people, but turned out to be something else. If it is not a true business rule, it might not belong to the model.
Business rules always live in the model. The model is the bit that you could resuse with a completely different UI. The view is obviously completely dependent on UI choices and the controller has to take data from the model and tell the view to render it.
Putting business logic into the view is bad because it ties the structure to the presentation.
Putting business logic into the controller is bad because it splits your business domain between the data persisted by the model and the rules in the controller.
A quote from a Wikipedia Article:
MVC is often seen in web applications, where the view is the actual HTML page, and the controller is the code that gathers dynamic data and generates the content within the HTML. Finally, the model is represented by the actual content, usually stored in a database or in XML nodes, and the business rules that transform that content based on user actions.
Is there any reason why you cant mix MVC and Ntier? Our application does just that. Our controllers are used for data validation and decide which Business Layer calls to make.
OurApp.Web - Asp.net MVC Project
OurApp.Business - Business Layer Library
OurApp.DataAccess - Data Layer Library
OurApp.Entities - Basically all the 'models' shared by all layers
Business rules should be in the model, NOT the controller. The controller and view are part of the presentation layer.
The model represents the domain's entities and functionality ..
The controller is merely a manager for taking user input and requests, performing actions in/on the model and mapping that to views in the presentation layer. The controller is not just a mediator either, the view OR controller may act upon the model.
This is an anciently posted question, but I like a rules repository to be completely independent of any part of an application. Multiple applications, multiple implementations of a business tier, should be able to access a static rendering of a business rules repository. Simple separation decisions such as this make a migration from desktop -> web, for instance, trivial.
In my architecture, View -> Model -> Controller -> Business Tier -> Rules Repository, i.e. the controller accesses coarse data as presented by the business tier/layer, feeds it to the model which massages it into a presentable form, and the view passively displays it. The business tier, which is re-usable across any presentation format, will have explicit rules and access to a subsystem with implicit rules. By design, each component is ignorant of the details of a component above it.
I think the issue is a matter of definition. It seems to me that the logic for presenting the screens in the order needed is a controller issue and I have seen some projects that use a rules engine to determine the order and what is required input from the user. This is not the same as business rules imho.
You guys are wrong the business rules live within the controller and not the model...

Resources