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

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.

Related

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.

What is the advantage of Model-View-Controller (MVC) over Model-View?

Could anyone give an example of why it would be advantageous to use MVC instead of a simpler Model and a View only.
Note: whether it's called MVC or MVP (Model-View-Presenter), I'm talking about the one where the View receives input, then the Controller will respond to the input event by interpreting the input into some action to be done by the Model. When the model changes, the View will update itself by responding to events from the model.
What is disadvantageous of simply letting the Model respond to events in the View and vice versa?
In MVC, if I changed the model in a way that affects the controller then I'll have to do changes in the controller. In Model-View, if I change the Model, I'll have to update the view.
So, it seems like we are introducing complexity by adding the "controller" part?
In MVC, the Model is blind to its environment, the view can be too - passing off (blindly) its events to the controller, which knows more about the view and model. So when all is said and done, the controller is the 'non-reusable' disposable part of the system, since it is the most context aware component.
if I changed the model in a way that affects the controller...
The the model should expose simple CRUD methods in such a way that those using the methods do not have to know anything about the passed update object, nor what really happens inside the model.
This means that the view, IMO, has to do a bit of work by creating the passed record, since Controllers are supposed to be stateless and the view is more persistent. Controllers get triggered and 'kick-in' do their work with a passed object and do not have a state.
The passed data is created by some sort of generic convention.
Let me go even further. Suppose you have a view, a tablegrid, and a control whose enabled property is dependent on item is selected in the grid -- you COULD create a view that handles both those controls and this logic internally, and that would probably be the way to go in such a simplified example.
But the more atomic your views are, the more reusable they become, so you create a view for every, yes every, control. Now you are looking at a situation where views have to know about each other in order to register themselves for the right notification...
This is where the controller steps in, since we want to stick all these dependencies onto him, the long term disposable one. So the controller manages this type of view-to-view notification scheme.
Now your views are ignorant as they can be and independent, thus reusable.
You can code a view without having to know about the system, or the 'business logic' as they like to call it. You can code a model without having to know too much about your goals (though it does help to tweak the model to enable it to return the datasets you have in mind).... but controllers, they are last and you have to have the previous two firmed up before you can wire things together.
Here is another thing to think about -- just as the Model is supposed to abstract-away and provide a generic interface to the underlying implementation of the data it is managing (the client does not know if the data comes from a DB, a file, a program setting, etc) -- the view should also abstract away the control it is using.
So, ultimately this means a view should not (caveat below) have functions/properties that look like this:
public property BackgroundColor{get;set}
Nor
public function ScrollBy(x,y){}
But instead:
public SetProp(string name, object val){}
And
public DoCmd(string name, object val){}
This is a bit contrived, and remember I said ultimately... and you ask why is this a good idea?
With reusability in mind, consider that you may one day want to port things from WinForms to, say, Flex, or simple want to use a new-fangled control library that may not expose the same abilities.
I say 'port' here, but that is really not the goal, we are not concerned with porting THIS particular app, but having the underlying MVC elements generic enough to be carried across to a new flavor -- internally, leaving a consistent and ability-independent external interface intact.
If you didn't do this, then when your new flavor comes along, all your hard references to view properties in the (potentially reusable/refactorable/extendable) controllers have to be mucked with.
This is not to mean that such generic setters and cmds have to be the interface for all your views abilities, but rather they should handle 'edge case' properties as well as the normal props/cmds you can expose in the traditional hard-link way. Think of it as an 'extended properties' handler.
That way, (contrived again), suppose you are building on a framework where your buttons no longer have buttonIcon property. Thats cool because you had the foresight to create a button view interface where buttonIcon is an extended property, and inside the view your conditional code does a no-op now when it receives the set/get.
In summary, I am trying to say that the coding goals of MVC should be to give the Model and View generic interfaces to their underlying components, so when you are coding a Controller you don't have to think to hard about who you are controlling. And while the Controllers are being (seemingly unfairly) set up to be the sacrificial lamb in the long run of re-usability -- this does not mean ALL your controllers are destined for death.
They are hopefully small, since a lot of their 'thinking' has been shoved off into semi-intelligent Models and Views and other controllers (ex: Controller to Sort a Grid or Manipulate a TreeView) -- so being small they can be easily looked at and qualified for reuse in your next project -- or cloned and tweaked to become suitable.
It actually reduces complexity by separating the workflow logic from the domain logic. It also makes it easier to write unit tests and makes your application easier to maintain and extend.
Imagine if you wanted to add a new data type. With the approach above, you would probably duplicate a lot of the workflow logic in the new class as it would be likely to be tightly coupled to the domain logic.
The discipline involved in separating the workflow logic into the controller makes it more likely that you will have fewer dependencies between workflow and domain logic. Adding a new data type would then be more simple, you create the new domain object and see how much of the controller you can reuse, e.g. by inherited from a controller super class.
It would also make it easier to change frameworks in future - the model would probably not change too much and so would be more portable.
Having said that, you might want to look into MVVM depending on what you are using as your presentation layer: Benefits of MVVM over MVC
Advantages of MVC/P (I am talking about Supervising Controller here) over MV include:
You can handle complex data binding code in the controller, if required.
You can test that complex presentation logic without a UI testing framework.
You can also have a graphic designer make your views, and not see your code, and not mess up your code when they fix your views.

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.

Can any processing be done on the model? [MVC]

I've decided to make a big push towards MVC for all new sites I make. I have a question about whether or not you can have any processing on the model level.
The case that brought up this question is a video site. I have a Video class (model) and one of the things I need to do when a user views the video I need the view to be logged in the database. I'm not sure if I need to add a query in the controller or if I can add a addView method in the Video class.
The basic underlying question for me is what kind of methods am I limited to in the models? Can it be anything or does it have to be only accessor (a.k.a getValue/setValue) methods?
Ruby on Rails has the motto skinny controller, fat model. This doesn't apply to just Rails and should be practiced with any mvc framework.
I think your model is exactly the place to handle this. Now, your model is necessarily composed of just your entity classes. Your model, in my opinion, would include your entities as well as any business logic that you need to implement. Your controller should just be handling I/O for the view, invoking model methods to accomplish the actions invoked by the user via the user interface (view).
Here how I would do this. It should be valid in pretty much any language.
The View would initiate a method call to the controller's OnView() method, then display whatever the controller spits back to it (in a controlled way, of course... I'm thinking your view is going to contain a video player component, so you're going to get a video of some kind back from the controller)
In your controller, have a method OnView() that does 3 things: instantiate the Video object (i.e. uses your data layer to get a model object), call the updateViewCount() method on the Video object, and display the video (by returning the Video object to the View, presumably).
The Video model object contains data representing your video and any houskeeping stuff you need, which includes updateViewCount(). The justification for this is that a Video has a view count (aggregation). If "view count" needs to be a complex object instead of just an integer, so be it. Your data layer that creates Video objects from their primitive representation on disk (database?) will also be responsible for loading and creating the corresponding view count object as part of the creation of the Video.
So, that's my $0.02. You can see that I've created a 4th thing (the first three being Model, View, and Controller) that is the data layer. I don't like Model objects loading and saving themselves because then they have to know about your database. I don't like Controllers doing the loading and saving directly because it will result in duplicated code across Controllers. Thus, a separate data layer that should only be directly accessed by Controllers.
As a final note, here's how I look at views: everything the user does, and everything the user sees, should go through the view. If there's a button on the screen that says "play", it shouldn't directly call a controller method (in many languages, there's no danger of doing this, but some, such as PHP, could potentially allow this). Now, the view's "play" method would just turn around and call the appropriate method on the controller (which in the example is OnView), and do nothing else, but that layer is conceptually important even though it's functionally irrelevant. Likewise, in most situations I'd expect your view to play a video stream, so the data returned by the controller to the view would be a stream in the format the view wants, which might not necessarily be your exact Model object (and adding that extra layer of decoupling may be advisable even if you can use the Video object directly). This means that I might actually make my OnView method take a parameter indicating what video format I want to get back, or perhaps create separate view methods on the controller for each format, etc.
Long winded enough for ya? :D I anticipate a few flames from the Ruby developers, who seem to have a slightly different (though not incompatible) idea of MVC.
Since you can use whatever model code you want with MVC (not just limited to LINQ) the short answer is yes. What should be done in the model is perhaps a better question. To my taste, I would add a ViewCount property (which probably maps to a column in the Video table, unless you are tracking per user in which case it would be in the UserVideo table). Then from the controller you can increment the value of this property.
With MVC, people seem to be struggling with fitting four layers into three.
The MVC paradigm does not properly address the data storage. And that's the "fourth layer". The Model has the the processing; but since it also addresses the data, programmers put SQL in there, too. Wrong. Make a data abstraction layer which is the only place that should talk to back-end storage. MVC should be DMVC.
Keep in mind, there are many variations on MVC and no real "right way" to do things. Ultimately, how you design your classes comes down to personal preference. However, since you asked for design advice, here are my two cents:
Business logic belongs in the controller. Keep it out of the model and view.
Out of the many variations on the MVC pattern, the passive view style seems to be the easiest to test. In the passive view, your classes are designed as follows:
Your controller is "smart: it makes changes to the database, updates the model, and syncronizes the view with the model. Apart from a reference to the model and view, the controller should hold as little stateful information as possible.
The model is "stupid", meaning it only holds the state of the view and no additional business logic. Models should not hold a reference to either the view or controller.
The view is "stupid", meaning it only copies information from the model to the UI, and it invokes event handlers which are handled by the controller. The view should contain no additional business logic. Views should not hold a reference to the controller or model.
If you're an MVC purist, then it would not make sense for the model to update itself or the database since those responsibilities belong to the controller, so it would not be appropriate to create an addView method to your Video class.

Resources