Can the V access the M in MVC? - model-view-controller

While using a custom MVC framework I found that the view can actually access data in the model. That was a bit of a surprise because I always thought the V must go through the C. It was something like
//this is completely made up but not far off
serverside foreach(var v in Model.GetSomeList()) {
<div>#v.name</div>
}
Do many MVC frameworks in any programming language allow the view to access anything in the model? When do i choose what should go through the controller and what is ok to access from the view?

Usually that "Model" is really like viewmodel, not the business layer Model object, although it could be the POCO version of the business object. Basically, the view is bound to some poco without any business logic.

Information flow in classical MVC.
Data in MVC should not go from model through controller to view. That is violation of the original concept.
If you read the original definition of MVC design pattern you will notice that Views are meant to request the data from Model. And views know when to do it, because they are observing Model for changes.
Modern interpretations.
In the original concept you were meant to have small MVC triad for each element in the application. In modern interpretation (as per Martin Fowler), the model is not anymore any single object or class. Model is a layer, which contains several groups of objects. Each with a different set of responsibilities.
Also, with the rise of Web there was another problem. You cannot use classical MVC for websites. Theoretically now you could achieve it by keeping an open socket and pushing a notification to the browser every time you changed something in the model layer.
But in practice even a site with 100 concurrent users will start having problems. And you would not use MVC for making just a blog. Using such an approach for even minor social network would be impossible.
And that was not the only divergence from the original concept.
MVC-inspired patterns
Currently, along with classical MVC (which is not even all so classical anymore). There are three major MVC inspired patterns:
Model2 MVC
This is basically same classical MVC patter, but there is not observer relationship between model later and view(s). This pattern is meant to me more web-oriented. Each time you receive a user request, you know that something is gonna change in model layer. Therefore each user request cause view instance to request information from the model layer.
MVP
This pattern, instead replaces controller with a presenter. The presenter request data from model layer and passes it to current view. You can find patterns definition here. It is actually a lot more complex, and I, honestly, do not fully understand it.
In this case the View is passive and will not request any data from model layer.
MVVM
This pattern is closer to MVP hen to classical MVC. In this case the controller-like structure (which actually would be more then a monolith class) request data from model layer and then alters it in such a way as it is expected by the (passive) view.
This pattern is mostly aimed at situation where developer does not have full controller over views or/and model layer. For example, when you are developing some application where model layer is SAP. Or when you have to work with an existing frontend infrastructure.
FYI: what is called "MVVM" in ASP.NET MVC is actually a good Model2 implementation .. what they call "viewmodels" are actually view instances and "views" are just templates that are used by views.

This is common. If you look at the Wikipedia page for MVC, this is what it says for the view:
A view requests from the model the information that it needs to generate an output representation.
MVC is an architectural style, so some people change it as they see fit. From the design intentions of the architecture this particular question is certainly not frowned upon.

Related

How strict is the mvc pattern with model and view interactions?

I am confused about how model and view can interact
I was making a simple to do app with mvc pattern and I saw an article which said you shouldn't pass the model values directly to the view, which made the project more complex than I thought (I am relatively new to programming and this is the first time I am trying out a design pattern).
But then later on I talked to someone who said that that is not true and you can send the model data directly to view, he didn't even use classes or some kind of grouping to separate the function he just put them in separate files.
I was wondering if there is a guideline that I couldn't find or we can do whatever we want as long as they are kind of separated. I would love an article or a guide to read up on as well.
Since, I am not 100% sure the context in which you are trying to apply the MVC pattern, a good generic explanation of MVC can be found in GoF's 1995 book, Design Patterns: Elements of Reusable Object Oriented Software.
In the book, they state the following.
The Model is the application object, the View is its screen
presentation, and the Controller defines the way the user interface
reacts to user input.
A more robust explanation can be found from Martin Fowler where he also
makes the case for a variation of Model View Controller that uses a Presentation Model.
If you are referring to Spring MVC then there is some magic that blurs the lines a bit. But in general, you have a controller that represents some screen or an encapsulated piece of functionality that the user (web requests) interact with. The controller serves up responses that are derived from the domain, usually via a Spring Service (i.e. #Service). The domain (Model) doesn't know anything about the View and the View may or may not know anything about the domain.
Given that, the View should be derived from the Model. But that's not always the case since sometimes how we present things to a screen is not the best logical way to model things in our domain - not to mention, the domain should be presentation agnostic. This leads into Fowler's argument for a Presentation Model, which is a model that belongs to the Presentation.
I call this a Presentation Model because it's a model that is really
designed for and thus part of the presentation layer.
Microsoft took that idea and ran with it in a variant of MVC called MVVM (Model View ViewModel).
You can read more about that in Microsoft's documentation on ASP.Net Core.
So, back to your original question of "Should you pass the model directly to the view?" If you are using MVC then the controller is what provides the interaction. But if you're really asking, "Can you bind your view directly to the model?" If your model has all the stuff you need organized how your view needs it, then sure. And if it's simple enough, maybe that's the way to go. Otherwise, you could go with something like a Presentation Model or MVVM.

Is data binding fundamentally incompatible with MVC?

Data binding establishes a direct coupling between the view and the model, thereby bypassing the controller. Fundamentally this breaks with the Model-View Controller architectural pattern, am I right in thinking this? Does this make data binding a "bad thing"?
Edit: As example, angular claims to be a MVC framework, yet one of its main features is data binding.
In my opinion Data Binding can be a valid implementation of the MVC Pattern since the data binding mechanism itself acts as the controller in that case.
For example in the mentioned angular it seems like the $watch function is a shortcut to implement features that are typical Controller responsibilities and features in an MVC-style way.
So in my opinion data binding is an evolution step that implements best practices learned by implementing classic MVC controllers.
UPDATE
But in original pattern sense I would characterize data binding more like MVP or Passive View.
But the differences aren't that sharp in my opinion since it always also depends on your UI technology.
Not necessarily, since you don't have to bind your Model objects to the view.
What I usually do is create simple DTOs (or Presentation Objects) that contain only the data I want to display, and that's what the View layer displays.
In that case, the Controller retains its function as a translator between actions performed on the DTOs and actions on the underlying Model entities.
Actually, when your data is abstracted properly, the act of pushing the content of your models to your UI is a repetitive task that normally lead to some kind of "helpers".
Let's say to push a list of items to a combobox. This is not necessarily part of the controller as you may want to share such functionality. Also pushing the value of the control (to keep it simple, let's say the text of a textbox) is repetitive and bi-directional.
Also here you repeat your self (think of DRY) and do the same thing over and
over again.
That's exactly the point where databinding comes into play. This can take over the tasks that anyway are identical for simple controls (checkbox, textbox, combobox). For grid control and the like it may be specific.
Have a look at mvc & databinding: what's the best approach?. Here I discuss what could be the optimum when using databinding in combination with MVC.
Data Binding does not directly couple the view and model, so it is not a Bad ThingĀ®. It is an integral feature of the MVC architecture, which the GoF Design Patterns book describes succinctly in chapter 1.
MVC decouples views and models by establishing a subscribe/notify protocol between them. A view must ensure that its appearance reflects the state of the model. Whenever the model's data changes, the model notifies views that depend on it. In response, each view gets an opportunity to update itself. This approach lets you attach multiple views to a model to provide different presentations. You can also create new views for a model without rewriting it.
It's a common misconception that MVC is a layered (3-tier) architecture. It is not. The model updates the view(s) directly. But this does not mean the two are coupled! A publish/subscribe design keeps the model and view decoupled.
This more general design is described by the Observer design pattern.

What are the main advantages of MVC pattern over the old fashioned 3-layer pattern

I am contemplating about using an MVC pattern in my new project and I can clearly see the main advantage of being able to put the data layer (the model) a little closer to the presentation layer (the view), which will allow a little increase in application speed. But apart from performance stand point are there any other advantages of MVC over the view-logic-data layered type pattern?
EDIT:
For those who's interested I just uploaded a sample PHP code that I created to test the use of MVC. I purposly omitted all the security checks to make the code a little easier to read. Please don't critisize it too much, because I know it could be a lot more refined and advanced, but nevertheless - it works!!! I will welcome questions and suggestions: Here is the link: http://www.sourcecodester.com/sites/default/files/download/techexpert/test_mvc.zip
The separation of concerns that's quoted as being an advantage of MVC is actually also an advance of a 3-layer/3-tier system. There too, the business logic is independent and can be used from different presentation tiers.
A main difference is that in classic MVC the model can have a reference back to the view. This means when data is updated the model can push this data back to possibly multiple views. The prime example is a desktop application where data is visualized in multiple ways. This can be as simple as a table and graph. A change in the table (which is a change in one view) is first pushed via the controller to the model, which then pushes it back to the graph (the other view). The graph then updates itself.
Since desktop development is on the decline, a lot of programmers have only come in touch with MVC in some web variant, e.g. via JSF in Java EE.
In those cases the model almost never has a reference to the view. This is because the web is mainly request/response based and after a request has been served, the server cannot send additional information. I.e. an update pushed from the model to the client would be meaningless. With reverse ajax/comet this is changing, but many web based MVC frameworks still don't fully utilize this.
Thus, in the case of web based MVC, the typical "triangle" between M, V and C is less there and that MVC variant is actually closer to an n-tier model than 'true' MVC is.
Also note that some web MVC frameworks have an intermediate plumbing part between M, V and C called a backing bean (Java/JSF) or code behind (ASP.NET). In JSF the controller is provided by the framework, and the view often doesn't bind directly to the model but uses this backing bean as an intermediary. The backing bean is very slim and basically just pre-fetches data from the model one way and translates model specific messages (e.g. exceptions) into view specific messages (e.g. some human readable text).
Beside
code reuse,
separating of concerns,
less coupling between the layers,
already mentioned by #bakoyaro and #arjan
i think that MVC is better than 3-tier when combined with the "convention over configuration" pattern. (i.e. "ruby on rails" or Microsofts "MVC for asp.net").
In my opinion this combination leads to to better and easier code maintanance.
In the first place it makes learning the mvc-framework a bit more difficuilt since you have to learn the conventions (a la controllers go into the controllers folder and must be named xxxxxcontroller)
But after you learned the conventions it is easier to maintain your own and foreign code.
Forget increasing application speed by moving to MVC. I have found the biggest benefit to be ease of code reuse. Once you move to MVC, there are no dependencies on the presentation of your data or the storage of the actual data.
For example you could write a servlet that served up .jsp pages as your presentation layer one day, and the next day write a web service as another presentation layer to your existing Model and Controller. Like wise if you want or need to switch your DBMS. Since accessing the Model is completely separate from everything else, you would just need to re-write just your data access objects to return the data in a way your Controller can handle it.
By separating concerns into 3 distinct pieces, you also facilitate true unit testing. Your Presentation layer can be tested free of the Model or Controller, and vice-a-versa.
On a side note, I've often felt that the MVC abbreviation was inaccurate. Whenever I see it I think of it as View->Controller->Model. The presentation layer will never have DAO code in it, and the model will never have presentation logic in it. The Controller is forced to act as a go-between.
Where 3-tier separates presentation from business and data access, MVC is a presentation layer pattern which further separates Model (data) from View (screen) and Controller (input).
There is no choosing MVC over 3-tier/3-layered. Use them both.

Why is MVC so popular?

I was originally going to make this a longer question, but I feel like the shorter I make it, the better you'll understand what I mean.
The MVC architectural pattern has 3 dependencies. The View depends on the model. The Controller depends on the View and Model. The Model is independent.
The Layers architectural pattern defines N - 1 dependencies, where N is the number of Layers.
Given three Layers: Model, View, and Controller, there are only 2 dependencies, as opposed to 3 with traditional MVC. The structure looks like this:
View ---> Controller ---> Model
[View depends on Controller, Controller depends on Model]
It seems to me that this style accomplishes the same goals and produces looser coupling. Why isn't this style more common? Does it truly accomplish the same goals?
Edit: Not ASP.NET MVC, just the pattern.
With regard to griegs's post:
As far as mocking, Layers still allows you to use the Command Processor pattern to simulate button clicks, as well as any other range of events.
UI changes are still very easy, perhaps even easier. In MVC, the Controller and View tend to mesh together. Layers creates a strict separation. Both Layers are black boxes, free to vary independently in implementation.
The Controller has 0 dependencies on the View. The View can be written, and time can still be saved with loose coupling.
Because you decouple the interface from the controller making changes easier.
Also consider the scenario where you need to get started on a project but the artwork won't be ready for weeks or months. Do you wait or do you write all the code required for the pages and simply then wire up the view to the controller.
At least that's what we did and we saved months.
Also it made UI changes easier to cope with because there wasn't any code in our aspx pages that did anything.
Our tests were also better as we could mock up anything including button clicks etc.
And if you're talking about the asp.net-mvc framework, there is no code in the aspx files and no viewstate etc.
In proper MVC the controller doesn't depend on the view afaik. Or maybe I'm not understanding it correctly.
The model defines the data.
The view defines what the output looks like.
And the controller is a translator from a model-understood grammar to view-understood grammar.
So essentially the controller is independent. The view is independent. And the model is independent.
Yes? No?
I'll be bold, and try to explain why your method didn't catch on.
The MVC pattern basically requires the view and model layers to agree on an API.
Since one serves the other and there are no dependencies inside the code it leaves the controller to behave generically, all it needs to do is take a certain structure in the view layer and call the matching API on the model layer.
You'll note that agreeing on an API between the view and model isn't really such a big deal it has to happen anyway. And what you get is good separation between back-end front-end development.
In your proposed solution a lot of development is required on the controller side. The controller will be required to understand all the elements in the view and to map them to the specific calls required on the model layer.
Since the controller is a single access point connecting many views to many models this can quickly get out of hand and end up being an incomprehensible controller module.
Look at some Struts2 examples to see what I mean...
I think I'm understanding your point:
Yes you can make the View only depend on the Controller only by making the Controller transform (using PHP as an example) the Model objects to non-Model objects like simple arrays.
As we already know, performing this transformation can be more effort than it's worth if the decoupling isn't actually needed. If the View uses the Model objects then it has this dependency. However, this can be relieved a bit by having the View depend solely on the Controller for its required input, which can be Model objects.
The Symfony PHP framework promotes this style of skinny controller shuffling between Model and View. You can still directly call upon the Model layer to retrieve objects within the View layer but it's strongly urged against for the coupling issues you bring up. Within the View you can call include_component() which actually goes back up to the Controller if you need to query the Model.
I haven't gotten back to this in a long time, mostly because I was still thinking. I was unsatisfied with the answers I received, they didn't really answer my question.
A professor, recently, did steer me in the right direction. Essentially, he told me this: Layers which separate Model, View, and Controller is MVC. In the vanilla MVC architectural pattern, the dependency between the View to the Model is often not used, and you effectively end up with Layers. The idea is the same, the naming is just poor.
Choosing a presentation pattern for a new or enterprise web development on the Microsoft platform is a daunting task, in my opinion there are only three; View Model, Model-View-Presenter (MVP) or ASP.NET MVC (a Model2 derivative).
You can read the full article here ASP.NET MVC Patterns
I'd like to add some more things. First of all for my point of view is we use the model as container for the information we want to pass and show on the view. Usually the action method into the controller ends with return view("viewName",model).The view itself probabily will change its layour against the model :
on the view :
if(model.something==true) {
%>
somethign to show
<%
}
At this poinf the definition of model is hard to find.
I can say (especially on enterprise conext) the are two "model"
one is the domain model/entity model or how you want to call it that wraps the data coming from the lower layers (database,etc) and the view-model who contain the information we wants to show plus any other information we need to hide/show portion of interface
The controller orchestrate the the views and is indipendent from the view but a bit dipendent from the model:
into the controller
pulic actionResult Index(){
....
if(model.BoolProperty==true){
return ("firstView);
}
else
{
return ("secondView");
}
}
I hope it makes sense
In my opinion ,you'd better try it in your programme , you can use ruby on rails ,or codeigniter( for php ),these great framework may be helpful to your understanding the MVC.

Is The Web's version of MVC different than traditional MVC?

I've done a fair amount of work on MVC on the web, and we're learning about it in my OOP class. I'm seeing some differences, and I can't tell whether that's because the Web's version of the MVC pattern is different than the traditional one, or whether I misunderstood it.
From my understanding, The model (your flat files, RDBMS', etc) is a generic data-housing object. The View (Browser, HTML, etc) is what the user interacts with, and the controller mediates between the users actions and the data. The controller is the most domain-specific part, and it manages the views, tells the model what it needs, and tells the views what to display.
In class, we have the Views matching what I just described, the Model contains a list of the views so that it can update them when the data changes, and the controller simply maps the user's actions to calls to the model and to specific objects (which may themselves, ask the model to update the views). What ends up happening is that most of the business logic is in the model, and it's tied very heavily to the simulation or application that is being written, while the Controller is reduced to a mapping tool between commands and methods.
What are your thoughts on this?
In a non-web interface the controller handles the inputs from things like the keyboard and mouse, choosing which views to render and what changes to make in the model based on those inputs. The view and model can be more closely related because the view can register callbacks directly with the model entities to be notified of changes and thus be updated based on changes to the model directly instead of being updated by the controller.
In the web world, views are necessarily more decoupled from the model. It must act through the controller actions because it has no direct access (after being rendered and delivered to the browser) to the model. The controller takes a larger role in this environment even though the only "input" it has to deal with are browser requests. In a sense, the coupling that used to occur with the view in non-web MVC is transferred to the controller acting on its behalf. Since there are no callbacks from the model to respond to (let's forget about "push" technologies for now), more business code is incorporated into the controller since it's the natural place to model business processes, though perhaps not validation.
In my understanding controllers in the web MVC pattern are just bridges between Models and Views, they simply grab the data from the Model and pass it on to the View. The Model and the View and independent and never talk to each other.

Resources