I want to ask that in MVC why do we need controller.why don't we just directly connect model and view.what would be the problem if we don't have controller ?
4 Answers
Separation of concerns, it makes the program more maintainable and allows us to add more functionality to different parts of the system without breaking other parts because they are independant of each other... https://en.wikipedia.org/wiki/Separation_of_concerns
So if your code for your domain and the logic of how it should be given to the view and then the code which handles the presentation of the data on the screen are all in the one place it makes it very hard for you to change parts of the domain code without having to change parts of the logic which moves it to the view and also the code which then presents it..with the controller we can move the logic into another class and make it independent of the view so when we are fixing or modifying our application we only need to concern ourselves with one part of the MVC model...
5 Comments
MVC is a Software Architectural Design Pattern and by dividing your code it makes it more readable, maintainable and portable.
If you remove the Controller there will be many downsides. Including but not limited to:
Your code structure will not be as clear as it is in MVC. Therefore more code will exist in Models. It is harder to read and maintain.
The code will lose part of its portability for example your Model(DB, Files, Data, ...) needs to contain View functions, calls and delegates as well. so if you want to use the same Model with a different UI framework you will need to rewrite it or edit it. Like porting an App from Mac OS X to iOS.
...
Controller works like a glue and it binds the Model and View together.
2 Comments
Controller is the place you connect 'model' and the 'view'. There are two different domains, two different languages; View speaks in "string language", application speaks in another (say Java Language).
There is a need at least for those;
- Converting view parameters; they are entered by user as strings, to language objects such as numbers, dates etc...
- Validating view parameters; they are coming from user, possibly malformed or even malicious.
- Creating model objects, (or directly accessing to the database).
- Error reporting, if something goes wrong.
- Updating the view to represent the new state of the model.
It's possible to hide/automate some parts of controller's job; declarative validation, automated model-object creation from requests, binding model-objects to the view layer (for example JavaBeans).
But that's not replacement of the controller;
Controller is not the code we write, it's the "logical place" some responsibilities are put into. Even if it's not visible, it's still there for people who used to think in MVC.