Why is MVC so popular? - model-view-controller

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.

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.

What's the controller in MVC pattern and why does it exist?

While working with Unity, I realized that separating Model and View would make my code more readable and straightforward. Constructing the whole model, all I had to do is just create some UI and bind it to Model.
But I still don't understand what 'Controller' is, and why does it exist. I don't think I had trouble when I directly bound View to Model, not through Controller.
So the question is if we can bind View to Model directly, why do we need Controller? What's the benefit of having Controller between Model and View?
At the highest level the Controller is the link between the View (displaying the UI/UX) and the Model (creating and managing your database and its tables).
True, it is possible to write code without any Controller usage but your Views will quickly get very cluttered and each file will be full of logic that is much more nicely stored somewhere else hint hint.
The Controller (and Model and some other places such as helpers) is thus the perfect place to sort out all the back-end code so that all you need to do is send a single field or object to your View to display.
An example is somewhat painful because by its nature the Controller is where you go to sort out your code as things get more complicated but this is a great article to get you on the right track! HTH
https://www.toptal.com/unity-unity3d/unity-with-mvc-how-to-level-up-your-game-development
I don't have years of experience, but in my understanding controllers provide a bridge across view and models. While view contain the pretty part and models contain useful parts the controller do the calls of functions passing values from database to view or inputs to model. That provide a way to avoid lots of injection like class A calling class B, calling class C, etc.
You can put rule business in controllers or in view, but thats not the expected in MVC architecture. The first important thing (for me) in software programming is readability, whats MVC provide.
if you've interest, search for other architectures like MVVM, to compare then.

Spring best practice to separate model from view in controller and jsp?

Is it a good practice to use Spring Controller class(with #ModelAttribute) and the jsp to prepare model at the same time or the model has to be prepared only by Spring and the view from the jsp?
The idea comes from this topic . I have a Controller class:
#RequestMapping(value = {"", "/"}, method = RequestMethod.GET, params = "mode=create")
public ModelAndView showCreatePage(#ModelAttribute("createForm") ApplicationCreateForm form)
{
return customMethod("some string");
}
and in my jsp I have:
<jsp:useBean id="createForm" scope="request" class="com.example.ApplicationCreateForm"/>
I do not need to populate the form with the information to be present to the user all fields are empty.
So from what I uderstand I have been declared ApplicationCreateForm bean twice, with the same scope - request.
Is it a good design practice to use both at the same time? Is there a reason for that? Does the second declaration(in jsp) give me more power, for example to override the model or it is complete unnecessary? Does the second declaration overrides the first one when both are present?
There are many things wrong with this implementation.
Is it MVC?
If JSP know about Model, why do we need controller. Lets remove the routing engine and use JSP directly to consume Model. But then the application will be monolithic. I believe you do not want that. We have two major flavours of MVC. In both, controller is the front facing object. It receives the command, interprets it, works with data layer and gets Model. If required the Model gets converted into a viewModel and then this object is passed to the view.
Why viewModel?
Say we are implementing paging on screen. We are showing list of persons. Person is your model here but your view also need to know page number, page size etc. Your model thus may not fit directly in this case.
Say we need data from multiple tables to shown on screen. This data is related in some way. Now will you pass separate model objects to view and let it do all the business logic? Ideally no.
Should not the design support DTO or ViewModel or Commands and Queries?
We want our application to be designed properly. As stated above we need to send data to view or clients (REST) after processing. Processed data may not map to you domain until unless we are just creating a CRUD stuff. What if you want to implement CQS or CQRS?
Where is separation, where is SOLID?
If my view is performing business logic then where is 'S'? If view knows about model and need to be changed in slightest of changes in model then where is 'O'?What if I want to separate queries from command (CQS) and scale the two things separately?
To conclude I would say, yes you can do this but it is not good if you are developing a decent size application or you think it will eventually be one. I have seen people using model entities starting from ORM, to controller to view. It will work but the question is do you want a monolithic and tightly coupled application. As per my experience the presentation logic (view) has very different logic and need of data in comparison of controller and same goes for your data access layer.
I think you should prepare your model fully in spring controller. Then view should be as passive as possible, ie. only showing model attributes received from controller while having no further knowledge about application logic. This approach gives you clean separation of concerns and you view is as independent as possible and can be easily switched for different view technology - eg. thymeleaf or freemarker templates. The whole idea of MVC is to separate presentation layer and by leaking business logic to view you create unnecessary dependencies.
Your view should be as simple as possible, as the logic leaked to view makes it very hard to test and reuse. On the other hand, if your logic is nicely separated, you can test it easily and reuse it easily. Ideally, business logic should be completly independent on web environment.
By defining you are creating tight coupling between your view and class com.example.ApplicationCreateForm, using spring mvc you achive loose coupling between your controllers, view and model it might happen that you change you model name but you still have same properties in it which might be enough for view, in above case you will need to update your view but it won't be required in case you are using Spring MVC.
Since spring comes with the concept of making things loosely coupled to make your code more testable, you should always keep in mind that separation of concern is your priority. So it is always the best practice to prepare your model fully in Controller, not in views.
Keep thing simple , make your controller responsible for preparing your model, and keep your views to display the model only.
So, a big NO to your question. The second declaration isn't going to make you powerful, rather help you to be tied up.

Can the V access the M in MVC?

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.

In MVC, why should the model notify the views, and why should the view have the model?

In my world, the model notifies only the controllers subscribed to the model's event. Then the controller tells the view what to do, for example adding a new row to a list.
The same with the view: the view notifies the controller subscribed to the view's event. Then the controller modifies the model as needed, for example setting the name of a person, and call the Save() method on the model.
Okay, I know I'm wrong, I don't think every article about MVC is wrong because I'm thinking in another way. The point in MVC is to seperate the UI from the data model. How does this come true when the view and the model reach each other? Why should they do so?
Thanks for Your answer!
Model-View-Controller is seen different ways by many people, but I like to think of it as a combination of several other patterns rather than as a single pattern. This may come originally from this note
The connection of the view to the model is an Observer Pattern, with the model notifying the view when it has changed. There's no need for the controller to be involved in this.
I completely agree with you on this one.
For every project i work on, i try to enforce this:
View --> Controller --> Model
So that every action or event in the view call a specific controller method. This controller method will do his job (validate, call other service, etc) then if persistence is needed, it will the call the associated ModelService to persist the data.
in my world, a view component should never call a ModelService without going thru a controller.
But that's just me ;-) (and almost 100% of the good architect and designers i worked with)
I like to think of the model as a transparent thing, adhering to some sort of scheme. Very easy to "read" by a view. I never make my views programmatic, in the sense that you can call all sorts of methods on it. Usually my view is HTML, my model has methods but is also capable of presenting itself as a plain data structure, and there is an intermediate: in the form of a template engine.
But, there are lots of variants for MVC. I don't think there are 2 developers who would exactly, exactly, agree on what MVC actually is. MVC is -in my view - a pattern to help you. It is not a law that is trying to hold your creativity back by exactly defining up to the last bit what you have to do.

Resources