Related
I have few gwt mvp design related questions:
Can we use event bus to switch views from one presenter to other via controller using custom event?
If above is true, can the custom event (say changeViewEvent) contain name of next view, on the basis of which controller can take a decision, which presenter to show?
Is it a good design to make views reusable(as a widget) in an application, though i don't agree with this, but will be happy if someone has any thing to mention in favor of this.
PS: all my views make use of custom widgets and there is no gwt specific widgets(buttons, checkbox etc...) in views.
You can do anything you want, but you have to consider the consequences. For example, if you switch views without creating a history event, a user may be thrown out of your app when a user hits a back button expecting to see the previous view.
I very much like the Activities and Places design pattern. It takes care of all of the issues (history handling, bookmarks, tokens, etc.) You can also extend it to add animation effects when switching views on mobile devices - mgwt does that.
I have few gwt mvp design related questions :
Can we use event bus to switch views from one prsenter to other via controller using custom event ?
This is a bad practice, unless you have real good reasons to do that. Since you're changing the view without having an impact on the url, you won't know what is a the state of a view at a choosen moment, you cannot get back to a previous view in an easy way, and finally, people will have difficulties reading the code, since you're out of the "standard".
The only reference for you should be the url, you cannot assume data is loaded neither the applicatio is in a given state: each and any view may be the start of the navigation story for your users, so if you get information from any other source than the Place, you're probably doing wrong, especially if your source is an event. the only special case here is you don't want users to enter your app in a certain view state, so you 'impose' that another url is called before, and restrict the access to the view through an event starting from a given application state
If above is true, can the custom event (say changeViewEvent) contain name of next view, on the basis of which controller can
take a decission, which prsenter to show ?
as said before, you're reinventing the wheel. It's far better to adapt to the existing mechanism that is well thought and covers the majority of cases. You can put a json formatter to tokenize your url while developing so it's not a nightmare to put variables in. And when you're done, create a nicer regular url format
Is it a good design to make views reusable(as a widget) in an application, though i don't agree with this, but will be happy if
someone has any thing to mention in favor of this.
depends on what you call a View. if it's the activitie's view then youm might need that in very few cases, it's better to inherit a basic view and fork its children for each activity (even if the view does nothing, time will show it will evolve differently): this is better since the base view contains what is common without the specifics of each child activity.
Finally if you mean a composition of widgets when you say, a view, then you should definitely reuse them, it will make you obliged to improove your widgets and compositions to be in a constant improvement, this will heop you for the rest of the project, and maybe for other projects
I'm still trying to understand what is the correct way of implementing MVC. This example #oracle says that view has access to the controller. And another tutorial #leepoint is indicating that the view has access to model. Are these different variations of the the MVC? In my case I was following the tutorial at Oracle site with some modifications(I have added a function in AbstractController getModelProperty, which will allow me to retrieve the value of the fields of the current registered models, but it also could me sense to pass the model as parameter(like indicated at leepoint tutorial) to simplify and probably optimise the data access for the view.
Thanks in advance.
Views are bound to models. Since views render models, they have to have intimate knowledge of the model, there's simply no way around it. Some views are generic, and these have "generic" models. Here, you may try and conform your actual model to the generic one so that the "generic" view can use your data. But even with these generic models, the views are still tightly bound to them.
Models manage data, the state. While a view has intimate knowledge of the model, the model is view agnostic. It simply doesn't care. This way you can have several views for the same model.
However, a model must inform others of changes to the model. Typically in java you use PropertyChangeListener's. This mechanism lets the model just shout out changes wholesale, and anyone interested can listen for these changes and act on them, for example your view.
A simple example is that you game object can take damage from a bullet, and it's reduced to below 50% health. The view can see that health has been reduced and change the image of the model (say adding smoke, or whatever).
The Controller typically is bound tightly to the view and the model. It knows the capabilities of the view (like it's size, and other areas of interest), and it knows how to change the model. Such as when mouse is clicked, the controller converts the mouse point in to a coordinate relative to the view, and from that determines what object was clicked. Once it determines the object that was clicked, it can set the model for the object to, say, "selected".
The model then broadcasts out that it's "selected" property has changed. The view sees this, finds the bounding rect for the model that changed, and invalidates that rectangle on its display.
Finally, Java comes around and tells the view "Hey, Rect 10,10,100,100 needs to be painted". And the view find the models in that rect, paints the new view of the object with a "selected" border, or whatever.
Thats how the whole cycle works.
It's both. MVC has a triangular relationship with each other, with the Controller on the top. The newer way to go is using MVP, where the Presenter sits between the model and the view.
It's better if you can keep as much of the model knowledge out of the view and only feed it information specific to it's viewing task. It does make your life easier in the long run.
... says that view has access to the controller.
yes, the view holds a reference to the controller for user gestures. (in a gui, the view and controller sometimes end up lumped together).
... that the view has access to model.
yes, the view usually holds a reference to the model(s) (it might have more than one).
... Are these different variations of the the MVC?
there are a bunch of variations.
... but it also could me sense to pass the model as parameter(like indicated at leepoint tutorial) ...
usually the model has views that are observers and the view updates itself when it receives an update message as opposed to being called directly by the controller. the former decouples the view more from the controller.
The Swing libraries are a very good implementation of the MVC pattern. Just study the API for a bit and it will all fall into place for you.
The Wikipedia Article on MVC nails the relationships pretty well: View has the Model, Controller has both the View and the Model, Model knows nothing about both View and Controller.
In some cases it may be advantageous to simplify the pattern by combining View and Controller.
In my class we have been learning about different designs such as MVC and MVP. I am currently writing an application that displays data in a JTable and a custom plot. My question is how should I go about communicating between the View and Controller.
As an example, I have a button that should import data from a file into the Model. What I think I want is the View to notify the controller that the user wants to import a file. The controller then does the necessary logic to do so. How should the view do so? I see a couple of options.
1) Have the controller create an innerclass that gets called whenever a user hits the import button. In this case the controller would have to call a method of the view to see what file the user wanted to import.
2) Have the view detect the event and then call an appropriate method in the controller passing with it the name of the file.
This begs the bigger question of whether or not the view knows about the controller? I know there isn't a correct answer to these things but what would be the best way?
As you may know, the Controller layer is, most of the time, tightly coupled to the View layer.
In the projects I participate as a architect or programmer, I never put business logic in a controller. Because I never saw any technology in which the layer that communicates directly to the view can be ported.
The controller layer should act as a service layer to the view. So yes. The view must know about the controller. And, if the previous statement is true, there's no problem the controller could communicate with the view.
I design my business logics (my #EJB or spring's #Service) in a completely POJO-based layer. That's my portable business layer.
The controller is just a bridge between the view and the business rules layer. It calls business methods, format their responses properly (sometimes) and send back to the view. In this context, the controller can be a web service, a managed bean, a test suite, etc...
One way or the other, the view has to know about the controller. In my experience, events generated by GUI (such as button clicks, drag-and-drops etc.) are best handled in the view itself, since they're particular to the type of view you're using (would differ significantly if your UI was voice-based, for example). Controller should expose APIs like
importFile(String filePath)
with your 1) approach, you'd have to modify the controller whenever you add a new view / change things around in the view. 2) approach is better.
I usually, make Views as Listeners of Controller. In this way I can have several different views of same controller. All views should implement some common interface. I provide access from View to Controller using constructor injection. So it can be smt like this
InterfaceWithMethodThatViewCanCall controller = new ConcreteController(new Model);
SomeView view = new ConcreteSomeView(controller);
controller.addListener(view);
Another way that I currently try to use is communication throw EventBus. I would recommend you to lock at GWT which MVP usage examples.
*Unfortunately I haven't read any good research publication on this topic.
You could potentially create Subjects which will be called by view and listened to by controller. That way view wouldn't know about controller, it would basically communicate with controller via Subjects.
In your example you would have fileImportedSubject and controller would listen to that, and on each emission it would change model accordingly.
So this is a neat way of communication between those two, but i would not recomend it for anything other that some simple apps. Because at some point you will create too many Subjects that controllers need to listen to, and at that point i think that this approach start to represent bad design.
I have a model with a reference to the view, a controller with references to the model and view, and a decoupled view, with no references to the above.
The controller has all the listeners of the view, and takes care of events by calling methods on the model and view. The model calls methods on the view in some of it's methods.
Is this bad for maintenance and reuse and should all view methods be called only in the controller? Also, i haven't set up the model as the observable and the controller and view(s) as observators, as seen in some examples. Is this common practice to do so?
I would avoid coupling directly from the model to the view, or at least only as very special circumstances (and even then, this might hint that the state being manipulated is not true model state, but presentation state.)
In general, the model uses listeners to notify of changes rather than a direct coupling to the view. The view can have a direct reference to the model, so that it can get the data to display. Although this may not be strictly necessary - all changes can be propagated from the model to the view as listener notifications, at the time the view needs it, but this is usually a bad idea, since it couples the rendering of the view with notifications from the model.
To sum up, the controller makes changes to the model, which notifies interested parties (including the view). The view has a reference to the model to retrieve data.
Following the classic MVC pattern, a model would not have direct access to a view. However, indirect access - such as via an observer - would be helpful to alert the view to changes in the underlying data.
The model should not know anything about the view.
The view should know how to populate itself given a model.
If you model is going to change it might want to make the view know of any changes so the display can change.
There are so many flavors of MVC, that i will decline to call any as "wrong".
See http://martinfowler.com/eaaDev/uiArchs.html
Look for one fitting flavor and go with it.
On the desktop Swing is a good GUI library. Check out this article to see how it relates to MVC. For the enterprise, take a look at Martin Fowler's Model View Controller pattern (330) for web-based applications. If you don't have his book (Patterns of Enterprise Application Architecture), I highly recommend getting hold of a copy.
There's a nice blog article at Sun.com: Java SE Application Design With MVC. It starts with explaining the "classic" MVC pattern where the view and model interacts directly with each other and then goes on with the newer "centralized controller" MVC pattern where the view and model can only communicate with each other through the controller (model is decoupled from view). It contains a Swing targeted example as well.
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).