What should not be inside an MVC view? - model-view-controller

From the limited amount of people that I've talked to regarding MVC web frameworks, I've heard people say that, forgetting about forms, a view file should ideally contain HTML markup, string manipulation and a few for each loops. I've also been told that if statements in views should be avoided if at all possible. Is this generally agreed?
EDIT:
The situation that has inspired this question is writing a navigation, I'm finding myself writing:
if secondary_navigation_item has children
...
I'm thinking, ideally, does this qualify as logic (that should not be here)?

Generally speaking, the View should not contain any server-side business logic. But it can still contain logic that directly pertains to rendering the view.
An example would be a view containing some sort of variant record, whose display depends on the setting of a particular field. For example, a record that displays different information depending on a sex field being set to male or female. Which, of course, would require an if statement.

To say that your views should not contain any conditional logic is just silly. How else would you generate UI elements like "new message" icons or flash messages—use a different view template for every possible interface state? It's like saying that your controller should not contain any variable assignments because data manipulation belongs in the model.
It's perfectly alright to have logic in your view as long as it's view-related logic. You shouldn't get caught up in absolutes or pedantic interpretations of the model-view-controller definitions. As long as you understand and apply the underlying concepts of MVC, you're on the right track.
Every rule has an exception, and there are cases where you would do string manipulating in a controller or even implement application flow in the view. Sometimes you just have to evaluate it on a case-by-case basis and apply a little common sense.

A view should basically contain:
HTML Markup
Javascript
CSS
Minimum of server-side code you may need to put into view
So, a View should typically contain the layout elements. The main processing logic should go in Controller.
More Info:
http://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller

Related

Where does language translation fit in the MVC pattern?

I'm building a multi-lingual web application using the MVC pattern as the starting position. The application has a number of forms that users will be interacting with and many of these forms will have fields that do a lookup from a database table, 'Province' for example.
If I need the options in these lists to be displayed in the users' language on the screen, I can see a couple of ways to do this:
In the model. When querying the model, I can provide the language that I desire the results to be returned in. This would allow translations to be used everywhere that data from the model is displayed without changes. However, this also means that the Province model in my example (plus all other application models) now need to know how to do language translations.
In the controller. I can query the model in the controller action as usual and then create a 'Translator' object that I can pass the results into before completing the action. This would imply that each controller action would potentially be duplicating the same translation code, violating the DRY principle.
In the view. Since the presentation of the application is generally expected to exist in the views, and the language of the user doesn't impact the business logic of the system, an argument could be made that language translations belong here. Especially considering that a page could also contain static content that will need to be translated. The downside to this is that it would complicate the views somewhat, especially for the front-end designers who will have to work around the new translation code.
Is there an accepted best-practice for where text translations belong in the MCV pattern for web applications? Does this change at all if I were to be loading the select list options via an AJAX call instead of at page load time?
Thanks for the help!
The best place to handle it is in the view. Your question only references dynamic data from the database, but you also have to handle the static information in your views as well. Best to handle both of those in the same place. A common practice in MVC for handling multiple language is resource strings, separate views for each language, or a combination of both. For information from the database resource strings would work well. You would store a token in the database for the options in the list (that token could be the English translation) and the view would get the appropriate translation from a resource for the specified country/locale. There is a good detailed explanation on this approach in this blog post.
If you need to translate part of your UI, then I would create a helper method that would read a resource file and output a translated string for that resources. E.g.
#Translate("NewUserHeading")
So regarding the UI, it makes sense to handle this in the UI.
If the data that you are going to translate at some point might be shown in a Flash client, or a mobile app, then it should be translated by a server and it should have nothing to do with your MVC application.
Honestly, any interaction with a database should be handled in the model, and that's the only thing handled in the model. Interpreting/organizing that data should be handled in the controller. I guess more information would be need as to where this translation is coming from and how that works to really give a solid answer.
The view will just display strings from a resource file. Including the correct resource file for the locale should do it. In Web applications, it's often a single language JS file defining the UI strings per locale, e.g, strings.en-us.js, strings.pt-br.js and so on.
Some strings do come from the server dynamically, the controller doesn't need to know about it, the model should just grab the localized strings and return is as part of the data request.
So it's either in the view (if it's static) or in the model, (if it's dynamic). Controllers should just translate data from the view to the model and from the model to the view
Another very important thing to consider is WHEN to Translate. Using a once-per-each-translation method like #Translate("NewUserHeading") is fine if you only have 100 translations on your page, but what if you have more?
Because think about it, translation is based upon language choice and that only happens once-per-page or even once-per-session. The way that the Kendo UI people do it in their demo is that way, when the User clicks a new language a new set of server files is loaded. That would mean having something like:
/src/html/en-us/
/src/js/en-us/
/src/html/es/
/src/js/es/
etc..
Check it out at https://demos.telerik.com/kendo-ui/grid/localization
It's a trade off of more work for better performance. The ultimate use-case of translation right now is https://www.jw.org/ with over 900 languages!

newbie to OO question

My question pertains to windows forms
Let's say I have a combobox for customer and orders, and depending on the selection made on those comboboxes I populate a datagrid for all the Order details.
I am interested in a double click event within the datagrid row.
Upon the event 2 things can happen:
the record was deleted.
one or both combobox was changed.
With no OO Experience, I am handling all that logic in the code-behind.
Is that a wrong thing to do? Should I be creating a class that returns a boolean whether to cancel the event or do something else if all the conditions are satisfied?
If I create a class that handles that logic then that class needs reference to datagrid and all the associated controls and their Previous values and current values.
I am just confused.
I'm not sure that this is an OO question: more about patterns.
If I were you, I'd look at MVC (Model View Controller), MVP (Model View Presenter) and so on. Martin Fowler is one of the main authorities on this subject.
MVVM is popular in WPF - not sure if databinding is up to it in Forms.
One of the key things is that testing is so much easier if you have logic separate from the display gubbins.
Object oriented way of doing things is something that no one can tell you in just a single shot. It's a whole new paradigm of thinking on how a problem can be solved in terms of few interacting objects. These objects are from the problem domain for which you are creating a solution.
From the question, I can easily pick out atleast two problem domain objects - one would be "Customer" and the other "Order".
May be your "Order" class is composed of various objects of "OrderItem" which is composed of a reference to one of the "Product", quatity and may be the price.
If this is getting a bit hard to understand, I'm pretty sure that you would atleast have a database with tables that provides persistent storage of data. The tables that you have, (in many cases) can correspond to the actual classes that you need to design.
You dont' have to design seperate classes that are actually going to work with the datagrid and other controls, that can stay be in the code behind. But all your business domain objects and the operations that can be performed on these objects must be encapsulated into classes.

MVC - Who formats the model?

Before rendering into a view model should be formatted:
multilingual data localized;
date, time values formatted;
numbers formatted.
Who performs all this formatting - Controller or View?
Am I right that all the formatting is performed by the Controller which creates so called ViewModel containing only formatted values and sends this ViewModel to the View?
Thanks in advance!
Eric Petroelje is right, but I would build helper a class(es) to get localised content/dates etc, because localisation isn't always in the views, e.g. sending emails with localised content. I would have something like LocalisationHelper.GetString("MyKey"), or LocalisationHelper.GetDate(Date.Now), where the LocalisationHelper knows the users current locale (maybe from Session).
Then use this directly in the views where possible:
<%= Html.Encode(LocalisationHelper.GetDate(Date.Now)) %>
Design Patterns 101.
Model is for storing data (usually database-backed).
View is for presenting the data (not manipulating it).
Controller is for manipulating the model and passing that to the view (choosing the right locale for instance would go here).
MVC doesn't necessarily mean you have 3 distinct classes, but rather 3 components or layers. These are abstract and don't necessarily have to be tied to one physical class. Inside your Controller layer, that can consist of any number of helper classes or whatever.
I agree with part of what cartoonfox is saying, everything is intertwined. For instance, if you develop a view for a shopping cart, but the model is containing birthday information, then it isn't going to work. It is simply a design pattern to help remove duplication of effort. When you have fewer variables and less noise, it is much easier to focus on what needs to be done and understand it very well.
I had a discussion with our team about using annotations to render forms on a web page. These annotations were placed in the model or entity class. You will often work directly with entity classes, so it eliminates quite a bit of overhead and duplication of effort if you put your annotations here. Because your annotations are placed directly on the model class, you cannot end up with a view for birthday information, it just isn't possible. In addition, by following patterns, you strip out the junk that doesn't add value to the end result. You simply write the business logic and close to nothing else.
Although the annotations were in the same class as the model layer, the presentation or view layer consisted of the annotations and the helper classes. It doesn't need to necessarily be distinct classes or boundaries.
Another example would be. I've worked on some PHP web "applications" in the past. I use applications because they were a monolithic block of code, more or less a single main method with all the logic in there (which is hardly a functional application).
If you don't abstract code into functions and simply use a single method, you will end up with a lot of duplication of effort. If you tried to understand that monolithic code block, you would be in for a heap of trouble (as was I, it was hard to learn what was going on, then I would find a similar block of code somewhere else and be dumbfounded why a few things were tweaked the way they were).
It can be done any way you want, but design patterns such as MVC help you simplify what you write in order to get it to work as well as more easily wrap your head around the solution. Another popular design pattern or approach is divide and conquer.
To answer your original questions:
In Java, localized data would be done transparently by the application. For instance, if you wanted US English locale support, you would create a properties file:
messages_en-US.properties
and then place all your US English content in there. Depending on how much content this may be, you might want to use a different approach.
For my application I have whole pages in a different language so what I do is this. My controller determines the client's locale or a best match. Then it chooses which view to display and passes the model (data) to the view.
If you need dynamic formatting for your date/times, then your controller is responsible for determining which one will be used. Then, your view is responsible for using that converter to format the value.
I'm using JBoss Seam so the MVC design pattern is still used, but more abstractly. I don't have actual 'controllers', but an interceptor which is responsible for handling a specific piece of functionality (determining the client's locale, then another for their date/time preference). My controllers that would be the equivalent of a Spring Controller are action components responsible for handling page actions.
Walter
The view is responsible for this not the controller.
To explain I need to elaborate a bit about what the "view" is:
In both web-based and traditional GUI MVC patterns, the View is responsible for the external representation of whatever parts of the model that are shown. If that means "formatting" data from the model then so be it.
The controller shouldn't format the data - because the controller is responsible for doing things to the model based on events/commands coming in from the outside world. The controller doesn't have anything to do with rendering the output.
Example:
I want to display a shopping cart with several order lines:
Adding things to the cart causes the controller to change what's in the cart model.
Changing my locale causes the controller to change a setting in the user model to indicate preferred locale.
Whenever the cart is displayed, the view has to ask the model for the order lines and decide how to display that - maybe doing locale-sensitive work.
The same customer could ask to see the shopping cart in multiple different currencies. That just means changing what it looks like in the view. It's still the same shopping cart for the same customer with the same things in it.
If this is a web-app made from web template pages, you might embed code to pull in localized messages e.g. <%= message_renderer.text(:insufficient_funds) %>. In this case the "message_renderer" and the template file are both part of the view.
Views aren't necessarily just web-based templates. In some Java-based frameworks for example, we put "view objects" into a velocity template. Those view objects are linked back to objects in the model, but they also perform on-demand rendering and formatting behaviour. Those are part of the view although they're not just a template.
It's a bit confusing with frameworks like ruby on rails and groovy on grails where they call the template the "view" - when a view is really more than just a template. Traditionally (in Smalltalk MVC and in Java's Swing) views are just code that can perform formatting, rendering and any other display-related behaviour.
All that stuff seems like presentation layer logic, so personally I think it should go in the view.
ETA:
I wouldn't advocate for having the view call service layer objects in the general sense, but for localization I think it makes sense.
For example, lets say you have lots of static text on your pages that you have tokenized and stored in a database in various localized forms. I don't think it would make sense for the controller to have to lookup and put all those text tokens in the model. Even though a text token lookup is technically a "service layer" operation, I still think it makes sense for the view to call that service directly via some utility class rather than having the controller do it.

Using MVC, how should one handle communication between Views? Between Models?

Question number three in my quest to properly understand MVC before I implement it:
I have two cases in mind:
The primary application
window needs to launch the
preferences window. (One View
invoking another View.)
The primary Model for an application
needs to access a property
in the preferences Model. (One Model
accessing another Model.)
These questions are related in that they both involve communication across Model-View-Controller triplets, a topic that I haven't found much discussion of in my Googling.
The obvious way to fix this is to wrap everything in a top-level "application" object that handles transactions between Models and allows Controllers to invoke one another's methods. I have seen this implemented, but I'm not convinced its a good idea. I can also see possibilities involving Controllers observing more than one Model and responding to more than one View, but this seems like its going to become very cluttered and difficult to follow.
Suggestions on how best to implement this sort of cross-talk? I feel like its a very obvious question, but I've been unable to find a well-documented solution.
On a broader note, if anyone has a link that shows typical approaches to these sorts of MVC issues, I would love to see it. I haven't had much luck finding solid, non-trivial references. Examples in Python would be lovely, but I'll gladly read anything.
Edit 1:
I see some pretty interesting things being said below and in general no-one seems to have a problem with the approach I've described. It is already almost a lazy form of the FrontController design that Vincent is describing. I certainly don't foresee any problems in implementing that pattern, however, it doesn't seem that anyone has really addressed the question in regards to communication amongst Models. All the answers seem to be addressing communication among objects in a single Model. I'm more interested in maintaining separate Models for separate components of the application, so that I'm not stuffing fifty state properties into a single Model class. Should I be maintaining them as sub-Models instead?
With respect to (1), views don't invoke other views. They invoke controller actions that may result in other views being rendered. In your case, the primary application window contains a user interface element (button, link) that invokes a controller action to display the preferences window.
With respect to (3), model components certainly could be related to one another. This isn't unexpected nor to be avoided, necessarily. For instance your Customer model may have an associated set of Orders. It would be perfectly natural to access the customer's orders via a method in the Customer class.
You might want to take a look at the MVC page on wikipedia for an overview.
You may want to consider looking up the Front Controller design pattern.
The Front Controller pattern defines a single component that is responsible for processing application requests. A front controller centralizes functions such as view selection, security, and templating, and applies them consistently across all pages or views. Consequently, when the behavior of these functions need to change, only a small part of the application needs to be changed: the controller and its helper classes.
This way all requests from the view goes to the FrontController who then decides which specific action (controller) to invoke. Sometimes, it could forward straight to another view as in your first case.
There is no problem with multiple objects in the model talking to each other. In fact that will be very common. The way I see it, all the objects in the Model act like one component to represent the data and operations on the data.
This article might help. And this one.
Model does not mean a single model object. The model is the subset of the entirety of your domain model which is directly related to the controller actions and the views in question.

Fat models, skinny controllers and the MVC design pattern

I just read a blog post that explains MVC with a banking analogy. I have a few months of experience with web application development with an MVC framework (CakePHP), so I get the basics, but I began to see a theme that made me think I'm taking a flawed approach to where I put my logic:
Fat models, skinny controllers
Keep as much business logic in the models as possible
In my app, models are anorexic and controllers are obese. I have all business logic in the controllers and nothing besides associations and validation rules in the models.
Scanning through my controllers, I can now identify a lot of logic that should probably go in a model:
The app has lists, which contain items, and the items can be ranked. The sorting logic which puts the list in ranked order is in a controller.
Similarly, items (Item model) also have images (Image model). Each item may have a default image (designated by image_id in the items table). When an item is displayed with its images, the default image should appear first. I have the logic that does this in a controller.
When a list is displayed, related lists are displayed in the sidebar. The logic to determine which lists are related is in a controller.
Now to my questions:
With the examples I gave above, am I on the right track in thinking that those are instances of logic presently in a controller that belongs in a model?
What are some other areas of logic, common to web apps, that should go into models?
I'm sure identifying this problem and changing my design pattern is half the battle, but even if I decide to take those examples I gave above and try to move that logic to a model, I wouldn't know where to begin. Can anyone point me in the right direction by posting some code here, or linking to some good learning resources? CakePHP specific help would be great, but I'm sure anything MVC will suffice.
It's a bit tough to give you the "right" answers, since some of them deal with the specifics of the framework (regardless of the ones you are working with).
At least in terms of CakePHP:
Yes
Anything that deals with data or data manipulation should be in a model. In terms of CakePHP what about a simple find() method? ... If there is a chance that it will do something "special" (i.e. recall a specific set of 'condition'), which you might need elsewhere, that's a good excuse to wrap inside a model's method.
Unfortunately there is never an easy answer, and refactoring of the code is a natural process. Sometimes you just wake up an go: "holy macaroni... that should be in the model!" (well maybe you don't do that, but I have :))
I'm using at least these two 'tests' to check if my logic is in the right place:
1) If I write a unittest, is is easy to only create the one 'real' object to do the test on (= the object that you are using in production) and not include lots of others, except for maybe some value objects. Needing both an actual model object and an actual controller object to do a test could be a signal you need to move functionality.
2) Ask myself the question: what if I added another way to use these classes, would I need to duplicate functionality in a way that is nearly copy-paste? ... That's also probably a good reason to move that functionality.
also interesting: http://www.martinfowler.com/bliki/AnemicDomainModel.html

Resources