With all the tutorial out there, I managed to make a view displayed by a controller. However, I don't understand how do I allow the user to navigate through the site with MVC. Every request to the server must go through the controller? If every request must go through the controller, how am I supposed to let the controller define the type of response it should forward the request to.
Edit: I'm doing a school project which required me to convert my current not reusable code to MVC pattern but I'm not understanding the navigation part of different views. How to get from one view to another view. For example, the navbar element should point to the controller or the view?
The controller comes first, it comunicate with the model and send you to the view you want.
So, for what you need, in the view, just put some link with the url mapped in the controller you want...
The short answer is that all actions "point" to the controller with a parameter telling it what the action is supposed to be, together with any other necessary parameters.
Suppose you have a simple registration form. You may have the following two actions: showRegistration and Register. MVC is not specific to the web, but I will provide the examples in that context (based on your comments). These two actions will point to your controller (say index.jsp) with URLs like this: /index.jsp?act=showRegistration and /index.jsp?act=Register.
Your controller will then have different logic for the different actions (you can do it in many ways yourself, or use some framework which does this switching logic for you). At the end of the day the logic in the controller will boil down to something like this:
if showRegistration:
model.getCountries //to populate a dropdown maybe
view.showRegistrationForm
if Register:
model.validateRegistrationForm
if not valid
view.showRegistrationNotValid
else
model.createUser
if userCreated
view.showSuccess
else
view.showCouldNotCreate
The idea is that the Controller contructs the full action using reusable model and view components. You can use the same model.getCountries in many different places, thus reusing the logic of retrieving a country list.
In practice, it requires a nontrivial effort to generalize the model and view actions. I've seen many projects decent into a chaos of hundreds of components created for a single purpose and used only once, and many components which are essentially duplicates because the developer did not know a similar one already exists, or needed slightly different logic and did not want to bother modifying the old code.
I'm trying to use the MVC design pattern for my project but I'm sort of unsure about how to decouple my program into the classes. The first part of my program is a Login screen which requires the user to enter a their username and password and a start button which checks the details, and there is a button to go to a page where you can add a new user. So I was thinking for my MVC design:
loginpanelView : Just the GUI with the text boxes, labels, buttons etc
loginpanelController:
- implement the actionlistener for the start button here and have a reference to the method checkLogin
- implement actionlistener for add user button here and have reference to a method which switches the panels
loginModel:
- defines the actual method which checks the login
switchpanelModel:
- defines a method which creates a cardlayout system and switches the panels
My understanding is that the controller just makes very general references to what needs to be done i.e. sort of what the user wants to happen, then the model defines the exact method of how to handle this? Would someone mind verifying/ correcting my understanding please? I've read a lot about this design pattern but unfortunately I still don't feel like I have a clear understanding of it. Any help would be much appreciated!
p.s. Sorry! I forgot to include that I'm programming in Java
It sometimes helps to think of MVC in terms of dependencies.
The model repesents what your application does. It has no dependencies on anything. It is what makes your application unique.
The view displays information to the user. This information comes from the model. Therefore, the view has a dependency on the model.
The controller's function is to accept input from the user, dispatch that request to the appropriate model functionality, and (normally) accept the return value and supply it for a view to render. Thus, the controller is usually very tightly coupled to the view(s) that it serves. It also has dependencies on the model.
In this case, the model is your authentication scheme. (In reality, this is not all that much of a model but an entry point in your application, your overall model is something like "process payments", "generate report", "request to create widget", etc.)
You have two views, one to enter authentication information and a second for when an authentication succeeds. The first really does not have any model information, it is solely to collect input (however its design will be based on whatever the authentication model needs, so there is still a dependency here). The second will undoubtedly display a list of available features your application offers or display a landing page etc.
It is the controller's responsibility to mediate these interactions. Therefore, information sent from the first view is received by the controller, dispatched to the authentication model, authentication succeeds or fails, and then the controller chooses the appropriate view to render based on the result.
With such a basic "functional design" it's hard to help you exactly, but you might want to think more about the big picture about what you want.
A user model - database model for a user. Contains a "check login"
method
A login-page View - Form, layout etc
A login controller - Gets the stuff out of the form, tries to log someone in with the method from the user object, and create said user
object
The page view/controllers can be split up ofcourse in several sub-parts, but this might not be a bad place to start.
It seems to me that LoginModel and SwitchPaneModel are not models at all. Model is what you store somewhere. So you will have UserModel and PaneModel. And your controller will implement switchPane method and login method. It's good idea to decouple this method in some separate classes there are lots of methods to perform this task. But I strongly recommend you to find ready solution. Don't invent the bicycle.
A good place to start is here. This is a special case of MVC called Passive View. The first important idea is that the view and the model do not communicate with each other at all. The view only tells the controller about events, and the controller manipulates both the view and the model. A controller can even create new controllers and views (such as for complex modal dialogs). And finally, the model does not communicate with anyone!
So you have the right idea: your loginpanelController listens for button events from the loginpanelView, and then calls the right methods in the model to set the data and validate it.
I think one place you may be having a problem with is switchpanelModel. I don't think you need this. If your loginpanelView is the view with the cards in it, then your loginpanelController should be the one switching the cards.
I think models should be restricted to methods working with its own data, but must have no reference to any GUI element anywhere. Models do not drive the program; controllers do.
Rather then thinking in terms of 'defining' a method, perhaps it is better to think in terms of what is being encapsulated.
For example, loosely, in MVC a view encapsulates primarily the user interface of your program (a login form), a model encapsulates some part of your domain logic (password authentication) and a controller encapsulates the logic that connects a view with a model (it depends there are variation of MVC architecture). The controller is often to some extent coupled to a view (especially if you start adding overtly specific ActionListeners etc) however the model should be quite reusable/exchangable (changing how you validate should not mean you have to change any view/controller that uses it)
I am working on an application and i am using the MVC pattern. Currently my plan is to have an MVC pattern for each window that comes up. For instance, my login window has its own mvc system. Another window where they make a selection has its own mvc system. Then the mainview has its own mvc system...
This just seems a little goofy. I was wondering if that was normal, to have every window have its own mvc? If not, how could i arrange this better?
The trouble i am running into is, how do i get the log in window mvc to correctly call the selection window and then after they make their selection, how does the selection window call the mainview window?
Thanks for any help! If you need more info, please let me know.
Despite its simplicity the MVC pattern is many time not understood. At first you need to understand what should be held into all of those separated components and how they might talk together.
The View : Any UI element. A good reusable view element should be reused anywhere. Therefore the view does not know it's context nor the specific controller he will be interacting with. What the view is aware is it's own state and one (or many) generic listener which it will call once some action happen. A view element knows it state, broadcast changes but should not change its state by itself. Example: A button will broadcast an action "clicked", and you will set the button name through a controller through a method like aButton.setLabel("click me!");
The model : A model is able to handle a state of a dataset, it usually implements some functions in order to save and load its state into / from a file. A model is a box which should actually not change its state unless someone (a controller) asks for it. Again, a good model is not aware of the view or even the controller. It is just the way it is. A very simple model is for example a String. You can load the string from a file, save it to a file, change it to uppercase, substring and so on. A string does have a state, is unaware of it's context and just wait for someone to use it. If the model knows the controller you are fooled, the model will not be reusable unless you implement the same controller (which is a bad practice even using interfaces).
The controller : The controller is actually your program, this is the part where the decision part is made. Where it is ? well… your main function is already the controller. Again, all the decisions are made into a controller. When someone clicks on a button, a method within a controller is invoked (and not a view one), when you want to update a label, you do it from the controller. Also all the threads should be handled into controllers. Your model is loading a large file ? Create a thread into the controller, ask the model to load the image, then notify the main thread once done (out of topic, search for event loop)
Multiple windows, here we are!
View / Controller how do they interact to each other ?
The responsibility of the view is only to provide to a controller events (text field changed, a button was clicked and so on) and to be able to be displayed the way we want. For example window.setTitle("myWindow"); We can be tempted to put stuff in the view that should be into the controller and conversely.
For example, if you are building an alert panel you will have 2 buttons (ok, cancel) and one label for the text. Do the view knows what to do once you click "ok" of "cancel" ? certainly not… but once clicked the panel will have to disappear by itself. Conversely, if you do create a panel for entering a password, the View will not be able to hold the validation process. This will be the controller's job to agree or not on the provided password.
Okay I guess you understood all the MVC, now it's time to talk about the right way to let all those components talk together:
How should the view be notifying the controller ? Actually it depends on the language you are using. At very first think of the following:
Avoid the view to know the controller.
The view should not be fetching information from the controller, nor invoking methods to it. How it will tell the controller something happened ? Through observers (or listeners)
Little parenthesis: A view can invoke methods of another view if it is just a matter of keeping it visually correct. For example resizing a window will ensure all the components (subviews) of this windows are still displayed correctly, but the controller might not be notified the window changed its size.
Communication between the MVC is the key! So, how does it work ?
Who will create and display a view ? The controller!
Who should be registering to view events ? The controller too… after creating
How ? The view's job is to broadcast events when they happen. Typically through ActionListener in java, observers in objective-c, lambda functions c++, function callback in javascript. And the controller to listed to it implementing the right "callback" function actionPerformed in java, a selector, or even directly the callback function if you provided a function callback to the view.
So when a view created from the controller is firing an event, the controller is notified and will have to handle this event. If the controller wants to change something into the view, it's quite easy cause the controller always own and knows the view.
To each window a controller : it sounds good, you are not obliged to have only one controller (neither one model or view…) while creating a login controller object instance, that one could create and display a login window as well.
One instance of model per service. Here comes the singleton design pattern, you will probably need only one "authentication model" because you are either logged in or logged out within the same application. So instead of creating several login model instance for each window dependent on the login state, you actually want to have only one. You can do this through a static instance of the login model object. This is called a singleton.
Now how to ensure that what we are changing into a model will be replicated to all the controllers ? The simple case is one controller and one model. The controller is changing the model and waits the model to be changed to then use the change (for example to display it into a view). What happen if the model is shared through several controllers ? For example, the model is a login service, you have 2 states : logged in and logged out.
2 controllers are using this model, each of those controller do have it's own view (window), one is just displaying a password field and the second one is a window with an image which is displayed only if the user is logged in. There is not one solution to this case but several. One is using the listening / observing pattern. Several controllers can be listening for the model's changes. Once one of those is changing it, all the controllers will be notified by the change and therefore will update the view. Another way is to keep a notification center (it's another pattern) and to let either the controller or the model to broadcast what happened, all the controllers interested in this event will then be notified by the change and process the event. This last solution is especially interesting for cases where the model can change at anytime (of course through a controller hidden somewhere). The notification center is using event loops and tries most of the time to notify into the main event loop (which should be your UI controllers's thread)
So for our example, if the login process is offline I would be using a simple listener. The 2 controllers are listening to the model changes. One controller after entering the password will call the method's model login.loginWithPassword(String some password) if the password is fine, the model will broadcast an event "loginStateChanged". All the listeners (including our 2 controllers) will then get this event and tell the view to get updated with whatever we want (for example display the image which can be shown only while logged).
In the example above, our controller was asking the model and the model directly fire the event, this within the thread of the controller, which is fine cause there is no risk of concurrency access (same thread = no problem) however:
If the login was a remote one, for example an online service authentication,we would be knocking at the server's door and wait for its answer. As this process might take some seconds the controller would keep stuck waiting for the server's answer. To avoid this case we should then send the request into another thread and just modify the view with a message (waiting for server) until we get the answer from the server. Once we get the answer (or after the timeout if no answer) the thread we created before will get the model's answer being true or false. A very bad idea is to update the view directly with the result. The problem is the thread who got the answer, is not running into the main controller's thread, and therefore if we do update the view, we do face a concurrency access (if the view object is changed by 2 threads exactly in the same time you encounter a crash). One way of insuring we are not messing with the main thread, is simply to send the model's answer to the main thread through a notification which will be dispatched in the main event loop. In this case especially I would be using a notification center instead of a simple broadcast from the model. It is interesting to note that some framework are providing broadcast within the main event loop. There is even better solution using block or lambda functions but it is but out of this question's scope.
To summarise:
Neither the view nor the model should know the controller
Only the controller do know both of them
Pay attention to the way they are talking to each other, use listeners or notification if there is more than 1 controller for the same model.
The process is always as follow:
The controller create the view and listen it
The view tells the controller an action happened
The controller process the action might ask the model to change something
The model gives a result (either returning the function, through a listener or callback)
The controller process the result
The controller update the view with the result.
How do I call that selection window from the login window correctly?
Use the observer pattern. If any view changes the model's state, then all registered listeners will be notified, and each can update itself to reflect the change. This example mentions three common ways to implement the observer pattern.
Actually i believe that what i am going to do is use a Mediator pattern to control the interaction between these views. This way the coupling is very limited and it gets the exact job done that i was wanting. Let me know what you think.
I think I understand the basic concepts of MVC - the Model contains the data and behaviour of the application, the View is responsible for displaying it to the user and the Controller deals with user input. What I'm uncertain about is exactly what goes in the Controller.
Lets say for example I have a fairly simple application (I'm specifically thinking Java, but I suppose the same principles apply elsewhere). I organise my code into 3 packages called app.model, app.view and app.controller.
Within the app.model package, I have a few classes that reflect the actual behaviour of the application. These extends Observable and use setChanged() and notifyObservers() to trigger the views to update when appropriate.
The app.view package has a class (or several classes for different types of display) that uses javax.swing components to handle the display. Some of these components need to feed back into the Model. If I understand correctly, the View shouldn't have anything to do with the feedback - that should be dealt with by the Controller.
So what do I actually put in the Controller? Do I put the public void actionPerformed(ActionEvent e) in the View with just a call to a method in the Controller? If so, should any validation etc be done in the Controller? If so, how do I feedback error messages back to the View - should that go through the Model again, or should the Controller just send it straight back to View?
If the validation is done in the View, what do I put in the Controller?
Sorry for the long question, I just wanted to document my understanding of the process and hopefully someone can clarify this issue for me!
In the example you suggested, you're right: "user clicked the 'delete this item' button" in the interface should basically just call the controller's "delete" function. The controller, however, has no idea what the view looks like, and so your view must collect some information such as, "which item was clicked?"
In a conversation form:
View: "Hey, controller, the user just told me he wants item 4 deleted."
Controller: "Hmm, having checked his credentials, he is allowed to do that... Hey, model, I want you to get item 4 and do whatever you do to delete it."
Model: "Item 4... got it. It's deleted. Back to you, Controller."
Controller: "Here, I'll collect the new set of data. Back to you, view."
View: "Cool, I'll show the new set to the user now."
In the end of that section, you have an option: either the view can make a separate request, "give me the most recent data set", and thus be more pure, or the controller implicitly returns the new data set with the "delete" operation.
The problem with MVC is that people think the view, the controller, and the model have to be as independent as possible from each other. They do not - a view and controller are often intertwined - think of it as M(VC).
The controller is the input mechanism of the user interface, which is often tangled up in the view, particularly with GUIs. Nevertheless, view is output and controller is input. A view can often work without a corresponding controller, but a controller is usually far less useful without a view. User-friendly controllers use the view to interpret the user's input in a more meaningful, intuitive fashion. This is what it makes it hard separate the controller concept from the view.
Think of an radio-controlled robot on a detection field in a sealed box as the model.
The model is all about state and state transitions with no concept of output (display) or what is triggering the state transitions. I can get the robot's position on the field and the robot knows how to transition position (take a step forward/back/left/right. Easy to envision without a view or a controller, but does nothing useful
Think of a view without a controller, e.g. someone in a another room on the network in another room watching the robot position as (x,y) coordinates streaming down a scrolling console. This view is just displaying the state of the model, but this guy has no controller. Again, easy to envision this view without a controller.
Think of a controller without a view, e.g. someone locked in a closet with the radio controller tuned to the robot's frequency. This controller is sending input and causing state transitions with no idea of what they are doing to the model (if anything). Easy to envision, but not really useful without some sort of feedback from the view.
Most user-friendly UI's coordinate the view with the controller to provide a more intuitive user interface. For example, imagine a view/controller with a touch-screen showing the robot's current position in 2-D and allows the user to touch the point on the screen that just happens to be in front of the robot. The controller needs details about the view, e.g. the position and scale of the viewport, and the pixel position of the spot touched relative to the pixel position of the robot on the screen) to interpret this correctly (unlike the guy locked in the closet with the radio controller).
Have I answered your question yet? :-)
The controller is anything that takes input from the user that is used to cause the model to transition state. Try to keep the view and controller a separated, but realize they are often interdependent on each other, so it is okay if the boundary between them is fuzzy, i.e. having the view and controller as separate packages may not be as cleanly separated as you would like, but that is okay. You may have to accept the controller won't be cleanly separated from the view as the view is from the model.
... should any validation etc be
done in the Controller? If so, how do
I feedback error messages back to the
View - should that go through the
Model again, or should the Controller
just send it straight back to View?
If the validation is done in the View,
what do I put in the Controller?
I say a linked view and controller should interact freely without going through the model. The controller take the user's input and should do the validation (perhaps using information from the model and/or the view), but if validation fails, the controller should be able to update its related view directly (e.g. error message).
The acid test for this is to ask yourself is whether an independent view (i.e. the guy in the other room watching the robot position via the network) should see anything or not as a result of someone else's validation error (e.g. the guy in the closet tried to tell the robot to step off the field). Generally, the answer is no - the validation error prevented the state transition. If there was no state tranistion (the robot did not move), there is no need to tell the other views. The guy in the closet just didn't get any feedback that he tried to cause an illegal transition (no view - bad user interface), and no one else needs to know that.
If the guy with the touchscreen tried to send the robot off the field, he got a nice user friendly message asking that he not kill the robot by sending it off the detection field, but again, no one else needs to know this.
If other views do need to know about these errors, then you are effectively saying that the inputs from the user and any resulting errors are part of the model and the whole thing is a little more complicated ...
The MVC pattern merely wants you to separate the presentation (= view) from the business logic (= model). The controller part is there only to cause confusion.
Here is a good article on the basics of MVC.
It states ...
Controller - The controller translates
interactions with the view into
actions to be performed by the model.
In other words, your business logic. The controller responds to actions by the user taken the in the view and responds. You put validation here and select the appropriate view if the validation fails or succeeds (error page, message box, whatever).
There is another good article at Fowler.
Practically speaking, I've never found the controller concept to be a particularly useful one. I use strict model/view separation in my code but there's no clearly-defined controller. It seems to be an unnecessary abstraction.
Personally, full-blown MVC seems like the factory design pattern in that it easily leads to confusing and over-complicated design. Don't be an architecture astronaut.
Controller is really part of the View. Its job is to figure out which service(s) are needed to fulfill the request, unmarshal values from the View into objects that the service interface requires, determine the next View, and marshal the response back into a form that the next View can use. It also handles any exceptions that are thrown and renders them into Views that users can understand.
The service layer is the thing that knows the use cases, units of work, and model objects. The controller will be different for each type of view - you won't have the same controller for desktop, browser-based, Flex, or mobile UIs. So I say it's really part of the UI.
Service-oriented: that's where the work is done.
Based on your question, I get the impression that you're a bit hazy on the role of the Model. The Model is fixated on the data associated with the application; if the app has a database, the Model's job will be to talk to it. It will also handle any simple logic associated with that data; if you have a rule that says that for all cases where TABLE.foo == "Hooray!" and TABLE.bar == "Huzzah!" then set TABLE.field="W00t!", then you want the Model to take care of it.
The Controller is what should be handling the bulk of the application's behavior. So to answer your questions:
Do I put the public void actionPerformed(ActionEvent e) in the View with just a call to a method in the Controller?
I'd say no. I'd say that should live in the Controller; the View should simply feed the data coming from the user interface into the Controller, and let the Controller decide which methods ought to be called in response.
If so, should any validation etc be done in the Controller?
The bulk of your validation really ought to be done by the Controller; it should answer the question of whether or not the data is valid, and if it isn't, feed the appropriate error messages to the View. In practice, you may incorporate some simple sanity checks into the View layer for the sake of improving the user experience. (I'm thinking primarily of web environments, where you might want to have an error message pop up the moment the user hits "Submit" rather than wait for the whole submit -> process -> load page cycle before telling them they screwed up.) Just be careful; you don't want to duplicate effort any more than you have to, and in a lot of environments (again, I'm thinking of the web) you often have to treat any data coming from the user interface as a pack of filthy filthy lies until you've confirmed it's actually legitimate.
If so, how do I feedback error messages back to the View - should that go through the Model again, or should the Controller just send it straight back to View?
You should have some protocol set up where the View doesn't necessarily know what happens next until the Controller tells it. What screen do you show them after the user whacks that button? The View might not know, and the Controller might not know either until it looks at the data it just got. It could be "Go to this other screen, as expected" or "Stay on this screen, and display this error message".
In my experience, direct communication between the Model and the View should be very, very limited, and the View should not directly alter any of the Model's data; that should be the Controller's job.
If the validation is done in the View, what do I put in the Controller?
See above; the real validation should be in the Controller. And hopefully you have some idea of what should be put in the Controller by now. :-)
It's worth noting that it can all get a little blurry around the edges; as with most anything as complex as software engineering, judgment calls will abound. Just use your best judgment, try to stay consistent within this app, and try to apply the lessons you learn to the next project.
Here is a rule of thumb that I use: if it is a procedure that I will be using specifically for an action on this page, it belongs in the controller, not the model. The model should provide only a coherent abstraction to the data storage.
I've come up with this after working with a large-ish webapp written by developers who thought they were understood MVC but really didn't. Their "controllers" are reduced to eight lines of calling static class methods that are usuall called nowhere else :-/ making their models little more than ways of creating namespaces. Refactoring this properly does three things: shifts all the SQL into the data access layer (aka model), makes the controller code a bit more verbose but a lot more understandable, and reduces the old "model" files to nothing. :-)
The controller is primarily for co-ordination between the view and the model.
Unfortunately, it sometimes ends up being mingled together with the view - in small apps though this isn't too bad.
I suggest you put the:
public void actionPerformed(ActionEvent e)
in the controller. Then your action listener in your view should delegate to the controller.
As for the validation part, you can put it in the view or the controller, I personally think it belongs in the controller.
I would definitely recommend taking a look at Passive View and Supervising Presenter (which is essentially what Model View Presenter is split into - at least by Fowler). See:
http://www.martinfowler.com/eaaDev/PassiveScreen.html
http://www.martinfowler.com/eaaDev/SupervisingPresenter.html
also note that each Swing widget is can be considered to contain the three MVC components: each has a Model (ie ButtonModel), a View (BasicButtonUI), and a Control (JButton itself).
You are essentially right about what you put in the controller. It is the only way the Model should interact with the View. The actionperformed can be placed in the View, but the actual functionality can be placed in another class which would act as the Controller. If you're going to do this, I recommend looking into the Command pattern, which is a way of abstracting all of the commands that have the same receiver. Sorry for the digression.
Anyway, a proper MVC implementation will have the following interactions only:
Model -> View
View -> Controller
Controller -> View
The only place where there may be another interaction is if you use an observer to update the View, then the View will need to ask the Controller for the information it needs.
As I understand it, the Controller translates from user-interface actions to application-level actions. For instance, in a video game the Controller might translate "moved the mouse so many pixels" into "wants to look in such and such a direction. In a CRUD app, the translation might be "clicked on such and such a button" to "print this thing", but the concept is the same.
We do it thusly, using Controllers mainly to handle and react to user-driven input/actions (and _Logic for everything else, except view, data and obvious _Model stuff):
(1) (response, reaction - what the webapp "does" in response to user)
Blog_Controller
->main()
->handleSubmit_AddNewCustomer()
->verifyUser_HasProperAuth()
(2) ("business" logic, what and how the webapp "thinks")
Blog_Logic
->sanityCheck_AddNewCustomer()
->handleUsernameChange()
->sendEmail_NotifyRequestedUpdate()
(3) (views, portals, how the webapp "appears")
Blog_View
->genWelcome()
->genForm_AddNewBlogEntry()
->genPage_DataEntryForm()
(4) (data object only, acquired in _construct() of each Blog* class, used to keep all webapp/inmemory data together as one object)
Blog_Meta
(5) (basic data layer, reads/writes to DBs)
Blog_Model
->saveDataToMemcache()
->saveDataToMongo()
->saveDataToSql()
->loadData()
Sometimes we get a little confused on where to put a method, in the C or the L. But the Model is rock solid, crystal clear, and since all in-memory data resides in the _Meta, it's a no-brainer there, too. Our biggest leap forward was adopting the _Meta use, by the way, as this cleared out all the crud from the various _C, _L and _Model objects, made it all mentally easy to manage, plus, in one swoop, it gave us what's being called "Dependency Injection", or a way to pass around an entire environment along with all data (whose bonus is easy creation of "test" environment).