the true implementation of MVC in JAVA [closed] - java

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
From week I have been searching of a true explanation and implementation of MVC using java, but something i have noticed is that every one implement it differently, so I would be grateful if you give me a useful link or e-book about it, and I need these questions to be answered :
How to inform the modal of the changes happen on the view, since the modal is observable adnd not observer ?
How to inform the view of the changes happen on collections (adding an item to an arraylist), because to add an item this will be happen on the controller handler and the controller is not observable.
Is it a must to work with MVC in the big projects.

The basic idea is:
The trigger for change can be either the controller
(=response code for user inputs, such as keyboard/mouse clicks), or application
decision. E.g. if you have a text field showing a price, the trigger to change it could
be explicit user typing, or a message from the bank.
each such trigger updates the model (and the model only).
In my price example, it would change the model (that backs the text field).
On change - the model fires events, which cause the view to re-render
Thus, to your first question: there's no need to "inform the model that changes happen on the view". The view shouldn't change on its own. The closes thing is keyboard/mouse clicks, that would invoke the CONTROLLER.
To your second question: "how to inform the view of the changes happen on collection" - the collection should be in the model. The controller would then do "model.addItem" which would fire an event for the view
Regarding the use in big projects... you'd probably get different opinions on it.
"Atomic" components would most likely follow this pattern strictly (button, textfield, or similar custom components). The debate would be about larger scales with complex/compound data. E.g. if my main logic resides on a database, how to I inform various screens that something changed. Both the screen and the database hold complex compound data (e.g. user plus his product recommendations plus shopping cart), and you need to decide on the granularity of events : on some simple applications I settled for the application layer sending 'Entity-level events' (such as 'user changed', 'product changed') to which the UI layer registered directly, so it wasn't 100% classical MVC. On other cases I took the trouble to build a compound Model that exactly reflects the screen data.

For the first part, I advise you to start at Wikipedia page on Model–view–controller. You will find a decent explain and other links.
For your first questions, you simply have to think about the workflow. The interaction with user occurs is the view. Then on an action of the user the controller takes the input, optionnaly reformats and passes it to the model in a format known to the model. In theory, the model then updates the view (in web applications, the controller collects data from the model and passes it to the view, so the update model -> view is indirect).
For the second, if you are in a situation where the model can directly update the view (Desktop application or specialized components such as java applets) no problem. If the model cannot directly update the view (typical in web applications), the update will be visible on next interaction. And in fact it happens exactly this way, when you see a web page with gauges displaying values constantly up to date : the browser is instructed via javascript or html meta tags to refresh its state at short time intervals. But when you say to add an item this will be happen on the controller handler, it is only true is this is caused by an interaction from the user (and the view knows it has to update its state, or is instructed to do so via the controller). But the model can be modified by many other ways, interaction from other users, real time probes, back office operations, etc.
The third question is a bit a matter of opinions. What is true is that separation of concerns is recognized as a good design because the different layers can be developped and tested independently (ot a certain extend). That separation allows to change technology in one layer without changing the others (even if this is often theorical). But IMHO the greatest benefit is that you have plenty of frameworks implementing MVC pattern. Choose one, and the greatest part of boiler plate code will be offered by the framework without you having to write and test it. All that giving a reduction of developpement time and of possibilities of mistakes.
My conclusion will be that (like others said in theirs comments) what is important is understanding the theory and the theorical benefits of MVC patterns and separation of concerns. Then depending of what you have to develop and you environment (technologies knowned or allowed) choose a framework that will exempt you to write boiler plate code, and spend the saved time to carefully analyze what all that is for, and what users expect.

Related

Draw sequence diagrams for a Java Swing application [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 days ago.
The community is reviewing whether to reopen this question as of yesterday.
Improve this question
I have a simple ATM system implemented in Java using Swing (I know Swing isn't really used anymore but I wanted it to be simple). The way I implemented it is as follows:
I have a Customer class which holds information about a customer and has a login() method
I have an Account class which holds information about an account and has methods for withdrawing, depositing and transferring money
I have a Transaction class which holds information about a transaction and has a generateReceipt() method that creates and exports a PDF with transaction info
I have an ATM class which holds the logged in account and the corresponding customer and has static methods for getting transactions, such as the current account transactions
Finally, I have an Admin class with username and password as attributes and methods for getting all the customers and accounts, adding a customer or creating an account and deleting a customer or an account.
My application uses a MySQL database for storing information and making updates. Also, customers can have multiple accounts and one can log in the system using the account number and PIN.
I drew the use case diagrams, and the class diagram, not considering my UI in the class diagram.
I have a hard time creating sequence diagrams for this application, as all my classes and objects are used in classes made with Swing.
My question is: how should I structure my sequence diagrams, considering the fact that it is a Swing application? Should I add the UI classes or should I make it more conceptual and only describe the process and relations between my other 5 classes?
Any help is highly appreciated!
I tried separating as much logic from the actual UI, but I still can't figure out how should my sequence diagrams look, as a customer and the admin interacts with the Swing frames.
The class diagram without any of the app's internals is a "domain model". Its goal is not to document all possible classes used in your apps, but to focus on the domain knowledge, independently of how the app is implemented. The diagram would stay the same if you had a real ATM device, if you would implement a web service, or if you would use any other UI framework.
So you made a clear choice on what you wanted the diagram to show. You could perfectly have chosen to have monstrous class diagram including in addition the classes required for the business logic, for database interaction and for the UI (e.g. using the famous Entity Boundary Control pattern). The diagram would then be more dependent on your implementation choices.
For the sequence diagram, it's the same. There is no best way to draft this diagram. The question is only about what you want this diagram to focus on: do you want to model the domain logic ? In this case you would use your domain classes and show how they interact. Or do you want to model the detailed application design , in which case you could envisage to add also UI classes. But the diagrams would then quickly become very complex, and you'd better break them down into several simpler SDs, each focusing on some parts of your detailed technical design.

MVC with swing implementation java [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 years ago.
Improve this question
I am confused how MVC will work with GUI swing application. I have worked with PHP MVC but that is totally different. I understand what MVC stands for. But what making me confused is different variation of doing it in GUI swing programming. It is hard to conclude particular thing from different articles in web. Who should know whom? I mean what will be the relation between model view and controller? Should controller know both model and the view? I would like to an simple example if possible to illustrate this (like and simple button which will update a label)
If i am not asking more i would like to get sugetions of MVC book which is writtern Swing in mind.
If you ask 10 different people "What does MVC mean?" you'll probably get 10 different answers. I'm personally partial to this definition of MVC (at least for non-web apps):
Model-View-Controller Design Pattern
Basically, the only functions the controller serves is to instantiate model and the view as the application starts up and connect them to one another. Everything else is just proper decoupling of your program's data and logic (model) from how you choose to display it to the user and allow user interaction (view).
There are many different interpretations of MVC for Java. I will try to provide a basic explanation, but as I said, others may disagree on this.
A theoretically 'pure' interpretation of MVC involves the following:
Model does not know about view
View does not know about model
Controller connects model and view in such a way that it provides data from the model to the view, handles 'events' in the view or the model, and updates the model accordingly based on what is happening in the view. It can also just handle an event in the view and provide a result back to the view, for example, a calculator.
Here is a possible/simple example:
The goal of this hypothetical application is to take a String in the model, get it to the GUI (view), allow the user to change the string, and update the aforementioned String value in the model. This example is more or less as decoupled as possible.
Model:
Contains a String variable
View:
Displays String variable.
Takes user input that allows change to the String.
Controller (the 'glue'):
Listens to Model via a customized listener for the String.
Provides this String to the view for the user to see
Listens to the view via a customized listener for the user to change the String.
Takes this new String and provides it to the Model, updating the original String.
One of the key things behind MVC is the Observer Pattern Theory.
Although one takes certain risks using wikipedia, it generally does a good job conveying the basics behind MVC. http://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller
Here is the link for a discussion on the 'pure' implementation and the source of the interpretation.
http://www.youtube.com/watch?v=ACOHAR7PIp4
Here is a link with a very good explanation of a similar MVC interpretation and the theory behind it:
http://www.youtube.com/watch?v=CVxt79kK3Mk

How to set up simulation architecture, OO design [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 years ago.
Improve this question
I'm building a simulation in Java. So, I'll break my simulation into two parts:
1) The simulation engine
2) The simulation model
Basically I want a little help (tips/advice) about how to split it up i.e. what goes where.
So I'm thinking that the engine will keep track of time. It will listen for events and when events arrive it will update the state of the simulation ( I'm building a discrete event simulation). The simulation model will have the GUI and it will get the logic and data from the actual engine. I'm thinking that the model will provide the actual events as input to the engine. I've been thinking about a car analogy where the engine is the body of the car and the model the driver. So I want it to behave like the driver(model) telling the car(engine) what to do i.e. when to turn when to break and what speed to go at etc
Do you think I'm tackling this in the right way? I can sense that I sound a little confusing and not very clear. So I'll just clarify that what I'm looking for is just some input to how I should split this up and what the responsibility of engine and model should actually be.
Also, I was wondering, if I were to implement the MVC design pattern, how would that fit in with the way I'm trying to break it up?
EDIT:
By model I mean that I want the simulation to have a set of specific rules which the engine then follows. As I'm building a road traffic simulator, the rules could be like, the distribution of cars, driver profiles, what cars may and may not do ( e.g. stop for red light) etc. So the model is like the "brain" of the simulation if you get what I mean, and then the engine being the actual simulation of the set of "rules" specified by the model. I hope this makes more sense.
May be not very applicable, but for MVC approach (Model-View-Controller), which is rather wide-spread and accepted, controller seems to correspond to what you call engine. And model is just that -- bunch of simple dump Java objects with as little logic as possible, containing only attributes of real-world objects they represent.
So, employing this analogy with MVC you'll get your model as set of roads, cars, containing just coordinates of objects and the engine will move cars, detect collisions etc.
After round of moves is finished, you'll get an updated version of model (some cars are in new positions with new velocity, some buildings are burning (heh), etc). And you'll handle this updated model to your view (whatever it may be) for rendering.
The only thing I'm unsure here is what part of the system is going to provide input events. In usual MVC this is some external entity (usually human operator). If by events you mean human input, it will be the same for your application. If you mean events like collisions because of, say, car's movements -- then it's engine itself who will produce such events as the result of calculations on each step of simulation.
Although, this not very classic OO design. In classic OO design, you would get model classes, such as cars, having their internal logic, which would define that, say, car is suddenly changes it's velocity out of the blue. I wouldn't go this route, because it makes logic of your code distributed between model classes and controller classes. You have set of model objects at the start of the world and the only way forward is to either influence them with engine decisions or to have real external input (like GUI input from human). If you need model object to change it's behavior, it should be responsibility of engine code, not model code.
Sorry for this rather incohesive speculation, this is rather wide topic and there are lots of books about such things.
You haven't given us enough information to REALLY help sketch out your simulation, but here's a good tip: Anything that you can identify as a thing should be an object. So make a class Car. And a class TrafficLight. Then make a class Driver, each Car has a field Driver. And a Road would have a List<Car>
Before you start thinking about how to implement an MVC framework, make sure you understand what it is.. The most important thing about MVC is that it's about how the user interacts with a universe. So you'd want MVC if, for example, you were writing a game called SimTraffic, because not only do you need a traffic simulation, but the user needs to control it somehow too. If you were just watching a simulation occur (with no interaction), don't worry about MVC.
Forget about the GUI. Please start from the physics - there are scores of traffic simulations; I assume you have read at least one book on the subject, if not it is high time to do so: a starting point could be a Springer-published collection of essays on various modern models called Fundamentals of Traffic Simulation (ISBN 1441961410), Jaume Barcelo (ed.) (2010).
EDIT: Would advise first deciding on the scope of your sim; what are the constant assumptions? For what time periods will it be tuned? Will road network change? Do you allow for car crashes, DUI idiots, onlookers taking movies from the crash site for Youtube?
What accuracy do you need from the sim - do you want it to be used for city planning, environmental control or traffic management? What are the variables and parameters that you set? Have you got statistical data to validate your simulation and test predictions against? Do you have ready data on physical characteristics of cars/drivers in your modelled universe/city (acceleration, linear size, propensity to break traffic rules)? There are a bunch of questions that should be answered before you sit down to code...
EDIT #2: from your comment to #Victor Sorokin 's answer, I gather you have a nice idea of adding driver's expectations into the model - would make the driver's AI the first thing to code: yes, shortest path, but the solution to the shortest path problem comes from stale data (with possibly variable delay). If you give drivers perfect foresight, there won't be any crashes; if you make them imperfect, you will have to model sensory input, perhaps boiled down to direction-specific probabilities of detecting an incoming car. It makes for some huge expenditure of CPU cycles, for sure.

How do you structure a java program? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 1 year ago.
Improve this question
For quite awhile I have been trying to make a simple "game" in Java that is really just an applet with a square and a grid. What I want it to do in the end is the user clicks and the square will move to where the user clicked rounded to the nearest grid square.
The problem is I am a self taught beginner and I am having a hard time figuring out how to actually structure the program, some examples:
should I have a separate class listening for mouse clicks?
When I receive a click should I send it to some other object that represents the box and let it decide what it wants to do or just call some function that makes the box move?
I really want to learn all this "when to use what" stuff for myself so any links or general advice is appreciated.
What you're really asking is how to develop a game, which is notably different from a typical Java application. However, I'll give you a few ideas to at least point you in the right direction.
Take advantage of the fact that Java is an object-oriented language. That is, objects should each have their own responsibility.
Separate your game into three key layers: the application layer, the game logic layer, and the presentation layer.
The application layer should contain all of your helpers and generic subsystems, things like random number generators, text parsers, file access modules, mesh loaders, etc.
The game logic layer should implement all of the rules of your game, and be responsible for maintaining canonical state. Basically, when you press the "W" on the keyboard to move forward, the game logic layer should receive MOVE_FORWARD_REQUEST from the UI.
The presentation layer should be responsible for two things: getting input, and rendering your world. When it gets input, like the "W" key, it should map that to an action, and send that to the game logic layer to be processed. Then, it should render the world based on whatever the game logic told it to do.
Game development is obviously an entire realm with many books dedicated to it. One of my favorites is Game Coding Complete, which does focus on C/C++, but should give you a good idea about how you ought to structure your game.
Good luck!
One main principle of good software development is the Single Responsibility Priciple. It states that a function or class should only have one responsibility.
This way your classes and objects shouldn't become too big and unmanageable.
I think one of the most important concepts to master when developing software is the concept or Orthogonality. It's not the simplest definition, but in essence it means that one component (such as reading mouse clicks) shouldn't be directly tied to an unrelated component (moving a square on the screen).
In your case, the code reading mouse clicks should be separate from the code that actually moves the box. Whether you implement this as inner/anonymous classes or not is up to you. But if you follow the Orthogonality principle, it will be easy to change at a later date should you change your mind.
One problem here is that all the rules have some leeway in them where you have to use your own best judgement.
For example, the app you are describing now seems to me so simple I'd probably do it in a single class, with perhaps a couple of nested, perhaps anonymous classes. In any event, I could make a decent case for fitting the whole thing into a single source file, claiming that multiple source files would actually increase the complexity of the whole thing.
But if your GUI had a number of different controls, perhaps each controlling different behavior, it would become time to split the functionality up so you're not ending up with a big bowl of spaghetti code.
The Java GUI libraries try to naturally separate (view+controller) from model. You are encouraged to define and display the GUI in one module (= file) but to have your data model and perhaps functionality in another. For complicated GUIs, there may also be multiple GUI implementation modules held together by code.
One way to keep things "clean" is to work in "layers" where each layer "knows" only what it needs to know. To be specific, the GUI layer needs to know about the existence of its underlying models – tables and lists and whatnot need to be connected to TableModels and ListModels, etc. It doesn't need to know about details of these models though, so it can simply refer to those models by interface.
The model layer, on the other hand, need know nothing about the GUI. The less it knows, the better, and this would theoretically enable you to exchange GUIs without needing to touch the models.
My model can also contain ActionListeners to respond to actions undertaken by e.g. pushing buttons in the GUI.
Of course, actions and changes to the model will often result in changes to the GUI. How to communicate these changes to the GUI if the model layer doesn't know about the GUI? You can use bound bean properties here. Here's a short tutorial: http://www.javalobby.org/java/forums/t19476.html . So you have the same kind of structure: Changes happen in your model, they're communicated to beans with property change support within the model, and the GUI can attach listeners to those properties to find out something changed.
Whether you perform actual, effective actions (e.g. writing files, converting data, whatever) within your model code or whether you split "processing" code off into yet another module is up to you and will again depend on how cluttered your model already is. If there's a tiny handful of fields and methods feeling lonely in there, you may decide to mash things together but the moment it starts to look messy you'll want to refactor your processing code out into its own module. Processing sounds like the kind of module that doesn't want to know about other modules either; you may end up just calling its methods from the model level.
I've described my basic style for doing GUI development. There are certainly other recommendations out there, and you will likely develop your own style based on your experience. This is just intended to give you an idea and a possible starting point.
Step 1 - find the demo applets supplied by Sun. http://java.sun.com/applets/jdk/
Step 2 - read those demo applets. At least three. Preferably all of them.
One you've read several applets, you should see a little more clearly how to organize programs. You can then ask questions with a lot more focus pointing to specific applet examples and your specific programming problem.
Yeah, I'm a beginner programmer myself. Yeah, segregating functionality across multiple classes is a good way to reduce complexity and increase cohesion of individual classes.
Increasing cohesion good because by having more complex data structure your algorithms become less complex and your code is less dependent on each other.
For instance in your case it might be a good idea to separate the classes in accordance to MVC (Model View Controler).
You have a Model which represents the way your game data is structured.
You have a Viewer which present your Model in what ever form you please.
Have a Controller which picks up changes in the Model (via Listeners) and then updates the Viewer
Now you can change your Model and add extra functionality requiring only small changes in the way the Viewer works.
There are many Patterns out there but there isn't a hard rule when to use one over the other. There are some cases in which you can use several and there are cases in which will require you to chose one design pattern over the other.
Every beginning Java programmer should start with the Sun Tutorials. They are quite good.
Another good source, especially among free sources, is Bruce Eckel's "Thinking in Java", available from http://www.mindview.net/Books/TIJ/.
But the latter is a little dated compared to the former. That is why I recommend both.

What goes into the "Controller" in "MVC"?

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).

Categories