Very simple MVC question - model-view-controller

I have a very simple question for MVC cause it is the first time i use it in my code.
I have 3 classes, the model, the view and the controller.
The question is :
Should I instantiate the classes separately and use them that way in my application or I can create a class that inherits this 3 classes and instantiate that class instead ?
Most importantly I don't want to violate the main MVC pattern.

You should instantiate the classes separately.
Moreover, it can pay to separate those classes into interfaces and implementation classes for later extensibility. For instance, if your model now reads date from file and later you need to be able to read the same kind of data from a database, you can then make a second implementation of your model class that implements the model interface. your controller that interacts with the model would then only need a change in how it instantiates its model. The rest of the controller implementation can remain the same (as it is has been written against the model interface).

Definitely three separate classes. The whole point of MVC is to have three classes that communicate (through the controller, which handles all the logic of the application). Creating a class that has all three in it would defeat the purpose of MVC.

In the more abstract way, inheritance should not be overused. With inheritance, you couple things together and make it harder to maintain. It contradicts with single resnponsibility principle (SRP) as well: "a class should have only one job".
Also, as any pattern, inheritance had better be only used it is neccessary and fits into the architecture correctly, for example: when there is a class Vehicle, classes Car, Bus and Truck should inherit Car: it is their nature.
So, in this current example, the answer is: It is correct to use model, controller and view classes separately, expecially when MVC pattern itself describes separating of these three parts :)

Related

How should I make a Class Diagram in MVC?

Here's my classdiagram:
In my perspective (since each cannot function without the next one):
models compose the repositories,
repositories compose the services,
the services compose the controllers.
I think I'm wrong in my understanding of UML relationships.
What is the right way to make a class diagram in MVC?
Terminology and semantics
If classes cannot function without another one, there is a dependency. A dependency does absolutely not imply composition.
In object oriented programming, we often refer to composition, in the sense object composition. This relationship is stronger than a simple dependency. It means that each object of the class may need to knwow objects of the other class. In UML we represent this with an UML association.
In some case, the links between objects are stronger, and may have UML aggregation or UML composition semantics. But it's not because you compose objects, that there is an UML composition. Same term, different meaning (some more advice on using UML association and composition and avoiding UML aggregation: here).
In MVC, the Controller is associated with the Views and the Model, and each Views is associated with the Model as well. There is no UML composition.
Notation
You cannot compose a class with a package. Packages describe namespaces and can be nested. They can contain other UML elements. But they cannot be associated/aggregated/composed with classes.
What you are looking for seems to be a component diagram: components can be nested, and be relate to other components via interfaces. And a component can contain classes.
Content of your diagram
There seem to be a slight confusion between the DDD domain model and the MVC model. Despite the same term, the two concepts are different.
In MVC, the Model manages the knowledge, meaning the domain model and everything needed to cope with the domain model:
User, Transfer and Tax are DDD domain entities/aggregates and belong to the MVC model
Everything needed to persist this knowledge, such as UserRepository, TransferRepository, TaxRepository also belongs to the MVC model. If you'd use another persistance approache (e.g. table gateways, or active objects) you would not have repositories but other objects.
The MVC Controller processes the user input, and sends commands to views and the model. It is not a repetition of the domain objects.
Where are the views ? What is the purpose of your services ?
are they domain service, i.e. operation that involve several aggregates and do not naturally belong to any single one of them ?
are they a service layer of an application, meant to link it with the outside world?

Does a Model in MVC Need To Be a Class Or is That Just a Common Pattern?

I realize I'm conflating / confusing two different topics, but it seems like in most popular MVC frameworks that I've come across the model is a class / object-oriented (and uses some sort of ORM or ODM that I might not want to use).
My question is: If I split my files into models, views, and controllers, but my model is simply a separate file that handles business logic, validates data and handles communication with a database... but I do it in my own way that isn't object-oriented... and maybe just uses super simplistic if statements for validation... is that still considered a model? Would that still be considered MVC?
Does the model need to be a class / object-oriented or is that just a super common pattern / preference?
Thanks!!
In general "Model" refers to your Business Object Model (BOM). If you subscribe to Domain Driven Design (DDD) then your Models in a Model View Controller (MVC) architecture will be representative of your BOMs as classes or interfaces. Those BOMs may also be your classes in an Object Relational Map architecture. Since it is better for an interface to be a description of what something can do and a class as a description of what something is, you would tend to see your Models represented as classes rather than interfaces. In terms of what "logic" is allowed inside of those model classes it is really up to you and your team. For example, while it is typical to put data validation in Models you may want to abstract those rules to a separate data validation class that your model uses. There is typically not a black and white rule about where business logic goes but it is generally considered best practice for each class to have a single responsibility based on the Single Responsibility Principle as part of the SOLID model. From my experience when I have called "Model" classes things that were not the Business Object Models, like a "RepositoryModel", it can be confusing about where the code representation of the data model was. Instead I recommend using the word "Model" to be reserved for things which end users are familiar with and avoid the word "Model" for things they cannot.

business methods in playframework contolles

Could somebody explain is it possible to have potected, pivate methods in playfamewok's contolles except:
public static void method-action-name() {}
For example if I would have method like this:
protected static int doSomeWork() {}
and this method would be invoked in method-action-name() ..
public static void method-action-name() {
...
int resul = doSomeWork();
...
}
I do not want to have long action-method, so I would like to split it to smaller ones, and then reuse it in other action-methods.
I mean is it ok (from playframework's point of view) to have such method in controller side instead of having them in domain classes? In Spring Framework, we use BP (business process) beans for that, for example.
Is it ok to have such helper methods for business methods in playframework controllers ?
Added after having answer & comments:
For example if I have SearchController class then for that class would be nice to have methods like preSearch1(), preSearch2() what search() method would use, but if I move these methods (1,2) to another class then it should be class with name like SearchHelper then? in package named /src/helpers.. not very nice because they related to search too. But maybe then into /src/bp/SearchBP (bp=business-process). And then in controllers/Search i use /bp/SearchBP that use some Model object with .save() DAO methods (SearchBP can use Domain methods and Search class can use Domain methods as well)
The question here: what class ant package would be nice for those methods? (i just did watch it in examples - there alway very simple usage of controllers that use domain object that why i ask)
yes, you can. Controllers are normal classes, you can add whatever you want. It may not be recommended to clutter them with helper methods, I personally would move them to another class, but you can do what you say.
ANSWER TO EDIT:
The name of the package is "irrelevant", won't change it too much :). You can put them under controllers.support.search which would mean controllers.support is a package with helper classes and the subpackage search contains helper classes and methods related to search.
One alternative (which I like more) is to create a Service layer for that, in a "services" package. You seem to come from a Spring background, so it should come naturally to you. These services are instantiated in the controller as required, or maybe just used via static methods, and do the main business logic. That way the controller only tackles the "higher level" logic.
Another alternative is to move as much of that logic as possible into the Model (avoidid the Anemic Domain Model), and using the Model classes from the controller.
As most decisions in development, which one is better depends on your experience, possible impact/limitations in the codebase, practices in your project... anyway, you can always refactor. Just choose the one that you are more used to (it seems to be Services approach) and code away :)
Any behaviour that's complicated enough to be described as "business logic" (rather than "presentation logic") belongs in the model, not the controller. If your model does nothing but map to/from a set of database tables, then it isn't doing its job properly. Things like permissions and access control, in particular, should be enforced by the model.

Best practices for implementing models in the MVC pattern

What are the best practices for implementing models in the MVC pattern. Specifically, if I have "Users" do I need to implement 2 classes. One to manage all the users and one to manage a single user. So something like "Users" and "User"?
I'm writing a Zend Framework app in php but this is more a general question.
The model should be driven by the needs of the problem. So if you need to handle multiple users, then a class representing a collection of Users might be appropriate, yes. However, if you don't need it, don't write it! You may find that a simple array of User objects is sufficient for your purposes.
That's going to be application and MVC implementation specific. You might well define a class collecting logically related classes, or you could define a static register on the user class. This is more of an OO question than MVC.
I'll second Giraffe by saying the use of included collections is almost always better than trying to write your own.
But I think your original question could be reworded a little differently... "Do I need a separate class to manage users other than the User class?
I use a static factory class to build all of my users and save them back to the database again. I'm of the opinion that your model classes need to be as dumbed down as possible and that you use heavy controller classes to do all of the work to the model classes.

How best to modify my model in Spring MVC if I care about IOC

I am building an application using Spring MVC. I want to make certain changes to my Model for every Controller in the application. In particular, I want to insert certain extra data into the model which will be present for all pages of the application.
I could do this several ways: just add the data at the end of every Controller, use a subclass of Model that adds my extra data, use a subclass of ModelAndView that wraps my Model, use a subclass of VelocityView that wraps the Model before using it... I'm sure there are other options.
But I have an "elegance" constraint: I don't want to write code in each and every Controller, I want this behavior defined in one-and-only-one place. Ideally, it would be controlled by my IOC bean config file.
Does anyone have a recommendation of how to achieve this elegantly?
Aspects are a good approach, but Spring MVC makes it even easier -- you can define a HandlerInterceptor that will be called before or after every time a request is handled. In the HandlerInterceptor postHandle method (in your class that implements the HandlerInterceptor interface) you can add your data to the ModelAndView. You define which handlers should be intercepted in your config file.
You could take a look at using Aspects. Spring even has an AOP extension that you could use.
In brief an aspect would allow you to define code once that would then get "woven" into your classes either when you compile the classes or when they are loaded by the classloader. It's relatively advanced stuff and isn't the most intuitive thing for new programmers to pick up, but it's intended to solve exactly the problem you're referring to.
I might be wrong, but I suspect that you may have described your requirements incorrectly.
You seem to be saying 'I want certain data to be added to my model, for all controllers'.
I suspect that you mean 'I want certain data to be available for all views'.
If my suspicions are correct, then adding the data to you model is polluting your model and violating the single responsibility principle. This is especially true if the same data is to be added to several models. Be careful that you are not just using your model as a convenient 'carrier' of the data - where the data doesn't really have anything to do with the model.
Admittedly, I'm not completely familiar with the Spring MVC way of doing things, but a more detailed example of what you're trying to achieve may allow for a more informed discussion.

Resources