MVC pattern with multiple classes - java

When I want to use the MVC pattern to a project which contains multiple classes what should I do ?
I should create a separate view, model, and controller for each of the relevant classes or use unique controller, view and model ?

This is is a very high level description because each of these main "components" could be made of multiple classes. So it is fully up to you to decide of the best mapping.
Other principles, such as the separation of concerns, would suggest to have different views for different model objects. So a UserAccount, and a UserAccountView is in general a sound approach. But you could still have combo views that refer to serveral different model objects at once.
You will find many more flavors of MVC regarding the controller. The single controller monopolizing the user input and controlling all the views and commanding the domains, is no longer a reality, since many windowing system attach the controller to a window. So you'd probably have a swarm of controller, with an AppController and an additional controller for each view, e.g. UserAccountViewController, rather than a controller per domain object.
Of course, in a very simple application, with a few relatively independent domain object, each having a single view, you could find the objects as you describe them.

It depends on the project's complexity and the purpose for which the classes are being used. If the classes are relatively simple and will be used to achieve a single task, then it may be more economical to use a single controller, view, and model. However, if the classes are being used for larger tasks and more complex interactions, creating a separate controller, view, and model for each relevant class may be beneficial. Ultimately, it is up to you to decide how best to organize the different classes to achieve the desired goal.

Related

Java-Use of knowing the differences between Entity, Vo, POJO, Javabeans, etc

I (think I) just understood the differences between Java Entity, VO, POJO, Javabeans, DAO, DTO, etc, I mean, the theory. Now, I'm trying to understand the implications of the implementations depending on the needs. Who cares if I create a POJO or a JavaBean? At the beginning I will create a POJO if I have no other constraint, until I realise I must make it a Javabean and deal with it's restrictions.
When do you tell yourself: "I need a DTO"? Only for web services or when any client/server call is made? In that case, do you put all the data you need (and the one you think you will need?) in one DTO bunch?
Lastly, in a MVC model, where does each one go? Can I make an entity or a vo in either layer? Where does the DTO go?
Thank you very much
You understood the difference between them, now you need to understand their purpose.
There is a neat definition for each one in this link.
Who cares if I create a POJO or a JavaBean? At the beginning I will create a POJO if I have no other constraint, until I realise I must make it a Javabean and deal with it's restrictions.
You need to think what the purpose of the class is. Is it a standalone class with no annotations that provides functionality but can be isolated (not counting libraries used)? Then it is likely a POJO.
Is it a class that serves as a bridge between layers of your project? Is it annotated? Does it implement some business logic for your project? Then it is a JavaBean.
When do you tell yourself: "I need a DTO"? Only for web services or when any client/server call is made? In that case, do you put all the data you need (and the one you think you will need?) in one DTO bunch?
DTOs are generally used to share information between layers. Their main purpose is isolating Entities so that you can change how your information is persisted from how the information flows through the different beans and controllers in your project.
To know when I need a DTO and when not I follow these rules:
Does the method more than three parameters? Then use a DTO.
Does the method return more than a single parameter? Then use a DTO.
When passing parameters to method calls / from method results: Does each element have more than one type (for Maps you would look at the value)? Then use a Collection of DTOs.
Otherwise use String, int, Long, etc.
Also never mind reusing DTOs even if most of its fields are not used for a specific method, you won't be wasting much memory if it's properly design. On the other hand, don't worry if you need to create new DTOs that share fields with some others, it might be clearer when reviewing your code. Try to find the right balance between too many DTOs and overpopulated DTOs.
Lastly, in a MVC model, where does each one go? Can I make an entity or a vo in either layer? Where does the DTO go?
It depends on how you structure your project. The term layer is a bit open as it can refer to each of the MVC elements and to the Data/Business/Client architecture (when I used the word layer in this answer, I'm talking about the later classification).
It is a good practice to separate each layer in a different project (specially in large projects). This is a common structure I use for enterprise web applications:
ProjectNameDao: Includes database access methods and entities.
ProjectNameBo: Includes all the business logic. Shares information with the other layers by using DTOs. It is, along ProjectNameDao, the Model in a MVC model.
ProjectNameWeb: Includes views and controllers from the MVC model.
ProjectNameDto: Includes all DTOs.
ProjectNameUtils: Shared utils, normally POJOs that hold constant values or provide basic functionality like Date formatting.
This structure needs to be adapted to whatever your requirements are, of course.

The task is to build Java project in MVC model and I am not sure about its structure

we got: one abstract superclass containing one method, and two subclasses redefining this method according to their needs. Not sure how to sructure project following MVC modeling.
Like, what exactly class model should have inside, controller and view?
In the most simple possible implementation:
Your model class should do data access and no more; say for example that it should be the only one with an import java.sql.whatever, and return collections of beans fresh out from your repository.
Your controller class should call your model layer, extract information and take a decision about what to show the user and how to do it. For example: you can read a list of organization units and decide whether to send the user to a tree view of the units or, if there is only one unit, send them straight to an employee table with the people on that unit. Spring MVC controllers or Struts 1/2 action classes are nice examples of this. It should also leave the data available to the view in some accesible place (for example, as request attributes)
Your view should be a JSP (or whatever view technology you use) as simple and with as few decisions taken in it as possible; all data is retrieved and navigation decisions are taken beforehand for it, and its only mission is to paint.

Doubts about MVC Model

I've been told that MVC is an architecture pattern for the presentation tier on a multi-tier architecture. I didn't understand the MVC Model concept.
So I made a web application, as an aproach to learn MVC model, only using JSP and Servlets, I made the DataAccess layer too.
In my WebContent folder, I put all the views.
In my src (Java content) folder, I made 4 packages.
data
presentation.model
presentation.controller
businessEntities
I used Servlets as Controllers (used the FrontController pattern) and JSP for all the Views.
As the title says, my problem is with the model.
Now, lets make an example..
I have 2 classes.
- Car
- CarLogic
CarLogic is a class that calls a possible CarDAO to get data and to return it to anyone who asks it. Car is just the POJO.
I placed CarLogic inside presentation.model and Car on businessEntities.
Am i wrong? What should i put on Model package?
Thanks!
When nested in the presentation layer of a multi-tier architecture, MVC's models are usually nothing more than (possibly enhanced) key-value maps.
The controller, after having called the appropriate business layer service, instanciate a new map with the values the view will have to display.
Spring MVC for example implemented the MVC pattern this way: see how the ModelMap extends LinkedHashMap.
See this answer to see a typical HTTP request life cycle, when the MVC pattern is nested in the presentation layer of a 3-tier architecture.
So to sum up, I would put CarLogic in your businessEntities package, and the Car POJO
within a new presentation.bean package for example (so you won't need your presentation.model package anymore). Thus, your controller would add the Car instance as an attribute of the request, which would then play the part of the model:
request.setAttribute("theBean", yourBeanInstance);
In your JSP views, simply use ${theBean.anyProperty} to access the attribute (don't forget the getter in your bean). Note that the EL will scan the following scopes in given order: page, request, session, application; the first found match will then be returned.
Model View Controller in and of itself is a pretty simple pattern.
From the wikipedia artical:
A controller can send commands to the model to update the model's state (e.g., editing a document). It can also send commands to its associated view to change the view's presentation of the model (e.g., by scrolling through a document).
A model notifies its associated views and controllers when there has been a change in its state. This notification allows the views to produce updated output, and the controllers to change the available set of commands. In some cases an MVC implementation might instead be "passive," so that other components must poll the model for updates rather than being notified.
A view requests information from the model that it needs for generating an output representation to the user
At least it was simple pre-web and pre-SOA.
The view part is still pretty straight forward, it simply presents the model.
Controller-wise, the web, in its traditional http/html sense rather than the newer JavaScript/AJAX/websocket sense, has made the controllers iteraction with the view much more visible than it was in say a Swing application. This means in addition to their traditional role, controllers in a web-app are likely to not only interact with the model but also have some knowledge of the views.
Model-wise, pre-SOA the model represented both the data and the behaviour of the business. More recently anemic domain models have become popular with behaviour implemented in separate classes from the representation of the data, which is passed to the logic classes (services).
It's this point, relating to the separation of data and logic that I believe your question relates to. Personally, for simple systems, I prefer a rich model with the data and behaviour in the same classes, hence the packaging is simple. However I appreciate that sometimes the benefits in separating the logic from the data and in such cases I'd create a separate package (and probably a separate jar) to contain that logic.
The word "model" means subtly different things in the term "model-view-controller", and when you say "model layer" in an n-tier architecture such as yours. From the point of view of MVC, everything the controller passes input to, and fetches viewable data from, is the "model".
This includes your domain model (Car), and business logic (CarLogic). You don't need to necessarily structure your application to exactly match the pattern you're using on the UI side. (In fact, the MVC pattern is probably insufficient to cover an entire application to begin with.)
So in your case, putting Car into businessEntities is fine. Not sure about having presentation.model to begin with – business logic isn't a presentation concern, and probably belongs in a layer on its own. Which is where I'd put CarLogic.
I have no idea what the data package is supposed to be at all.
This split means there doesn't seem to be a dedicated presentation model in your application. This might or might not be an issue. In a web application, what the presentation model usually does is encapsulate user input, or maps the business entities to a structure that fits the needs of the view better – flattening complex relationships etc. (In classical Spring MVC, these would be the Command and Model classes.) In a simple enough application, or using an advanced enough web framework, it's possible to directly use domain model entities in your views.
As an example of what a distinct presentation model would do, consider the internal system a school would use. You'd have a bunch of students, and some classes they can enroll in. At the business entity layer, you'd probably have a separate Enrollment entity that would hold attributes like date of enrollment, references to the grades a student got in the class, etc. However, when a view in the application needs to display the list of classes a student is enrolled in, it doesn't really need to see the Enrollment object at all. Thus it makes sense to have a presentation model object Student that only has a list of Class objects in it. (And the requisite code that reads the business entities and maps them correctly to this structure.)
From Wikipedia about MVC:
Model–view–controller (MVC) is a software pattern for implementing user interfaces. It divides a given software application into three interconnected parts, so as to separate internal representations of information from the ways that information is presented to or accepted from the user. The central component, the model, consists of application data, business rules, logic, and functions. A view can be any output representation of information, such as a chart or a diagram. Multiple views of the same information are possible, such as a bar chart for management and a tabular view for accountants. The third part, the controller, accepts input and converts it to commands for the model or view.
I highlighted one sentence, that usually is not understood. The model is a really rich model. That means, it also contains every logic that works with the data. It is up to you, whether to have separate classes for data and for logic (which reduces the data classes to structs or records), or whether to have richer data classes that already contain some business methods (the way that I prefer).
That said, the controller is just the interaction between the model and the view. In Swing applications - for example - the controller is nothing else than the various listeners (an ActionListener, for example).
So, to answer your question: Having a separate data access layer is a good thing. This is where your DAO class belongs to. The data and logic classes (the model) belongs to the model package. I would not create several packages for them.
MVC is a common design pattern used by many modern web frameworks, f.e. GRAILS, Spring MVC or ASP.NET MVC. You see the MVC pattern is included in their names ;)
For the MVC-pattern you actually need three packages:
model
controller
view
In the model package you put your classes which will be used to hold your data. The controller classes contains the logic to controll which view is called and which data should be used in those views. The views itselfs contains the information how to display your data on the screen. There shouldn't be any great logic, f.e. just JavaScript. The business logic should contained in a separate package. If you need this logic, you can call is from your controller.
Your packages are (I hope i read them correctly!):
data
presentation.model
presentation.controller
businessEntities
According to the MVC-pattern is suggest the following usage of your packages:
"data" or "model" - use this for your Car class
"controller" - use this for your controller logic
"presentation" or "views" - use this for your views to display your data on the screen
"businessLogic" - use this for your CarLogic class
MVC stands for Model View Controller.
Model is where you store entity objects
View you store Presentation objects
Controller is where you map your attributes that are present in the Model to the widgets.
so that the attributes are set to the entity objects from the widgets input.

How to design the interface for the Model in Model-View-Controller?

I understand how the MVC pattern works, but I've always had this question. If you have a big Model with many functions delegated to various classes, do you have to define a big monolithic interface with all the methods to manipulate and query the Model?
Or, can that model be partitioned to many models, that talk to each other, and then you can manipulate them with their respective controllers?
Thanks
The "ViewModel" concept may be helpful here -- it's also referred to as "view specific model" by Phil Haack in the book "Professional ASP.NET MVC3".
A lot of auto-tooling or "scaffolding" generators look to create a single page/interface but there is nothing preventing you from making a multi-stage process for a large model.
One option would be to create View Models for each stage of the process (ie. BigProcessPartAViewModel, BigProcessPartBViewModel, etc) and then generate a controller that process each of these with separate views. Obviously you'll need to manage state across multiple stages, perhaps with a database or session.
Additionally, your model is your model... it is NOT data access. So you may need to have an additional model that handles in-process state as well as a data access design that allows for a multi-phase transaction.
There is nothing that says that your Model needs to be a single class or entity.
For example, in Spring MVC, the model is basically a Map that you construct in the Controller, with keys and values.
Interface segregation is one of the SOLID which stands for 5 basic principles of object-oriented programming and design. It says that if your interface becomes too 'fat' it needs to be split into smaller and more specific interfaces. More details on Interface segregation wiki page

MVC pattern: which is better? For views or controllers to create and reference the other?

We are making a rather large Swing application which has to implement the MVC pattern.
The application currently looks like this:
There are quite a few views. They are created in a hierarchical manner where one main view contains (and creates)
several views which all contain their own set of sub-views, etc. Each of these views retrieve information from the model
independently from the other views, by calling the models static methods when necessary.
There are also quite a few controllers which are all totally separated from each other. Each controller
belongs to a view. Each view creates its own controller, and adds the controller as a listener to user input.
The controllers receive events from the views and then modify the model through the models static methods.
When the views dispatch events which do not affect the model, but only affect
the views, the views take care of these events themselves - without informing the controllers about the events.
That is, the controllers are totally unaware of the views, and the controllers purpose is only taking care of the manipulation of the model.
|EDIT: the controllers are currently attachments to their views; they only contain logic for event-handling. That is, the controllers are not components themselves, and do not contain components. They are implemented in the same manner as the following example: MVC example |
The model in the application is very passive, and does not even have listeners (it represents a database).
It receives updates from the controllers.
In this example, the views own the controllers. Would it be better in the general case if the controllers owned and created the views, and if one let the views be unaware of the controllers, instead of the opposite? In that case, why?
How would this be designed? If not, is there a better design in which the controllers are still unaware of the views? Or perhaps, is the best design neither of them?
EDIT:
As stated in the Original MVC definition:
the line "The View takes responsibility for establishing this intercommunication..."
seems to indicate that the view creates the controller, or at least has the initial reference to the controller, and not vice versa.
So this is at least a possible way to do it (it is a valid MVC pattern), but the main question remains; which is better, and how would the best design look like?
Especially when dealing with many controllers that are closely related to their respecive
views?
EDIT: Another example of a view which references a controller: Oracles example
As seen in this outline, the controller has the model and the view(s). Any sub-views are managed by the respective parent view. Sub-views may forward events to the parent as discussed here. There's a simple example here with more links.

Categories