Where to format non-standardized data into a standard format (View, Service, or DAO layer)? - spring

I am using Spring MVC for my presentation layer, and am also using Spring for my Service and DAO layers. Normally I would format data in the View layer of MVC (in my case JSPs), but what if the data that is retrieved from the database is not in a standardized format?
For instance, I am pulling phone numbers from one of my company's databases, but they could potentially be in any format (111)-555-1234 or 1115551234, etc. This seems like it would be too much functionality and processing to place in the JSP/View layer. I would prefer to put all of the numbers in the same format somewhere else and then re-format on the View. Where should I format in this situation - Service layer? DAO?
This would also allow me to take advantage of libraries that I could not potentially call from a JSP (or that would not make sense to call from a JSP).
Thanks!

I would have the DAO query methods remove the formatting characters from the phone numbers, and have the presentation layer give them a consistent format (probably in JSP tags). I am not a fan of putting business logic in DAOs, but this seems extremely data-related.
(Actually if the formatting code first removes any pre-existing formatting before doing its own formatting, you might be able to get by without removing formatting characters anywhere else. I just like having things in a canonical form.)
As an alternative to putting the formatting-char-removal in the DAO, if you are using Hibernate then you can create custom user types that remove or insert formatting characters from the phone number attributes.

I generally do formatting, when I map the Model to Value object (VO or whatever you want to call them), mostly in the presentation layer (or i put a layer in between the presentation and service layer, If I have too many things to do). This brings consistency in the format across the application, if that is what you want.
When i want the name to be in camelcase, I do this
BeanUtils.copyProperties(userAccount, userAccountVO, ignoreProperties);
userAccountVO.setName(StringUtilities.convertToCamelCase(userAccountVO.getName()));

Related

In MVC, should the Model or the Controller be processing and parsing data?

Until now, in my MVC application, I've been using the Model mainly just to access the database, and very little else. I've always looked on the Controller as the true brains of the operation. But I'm not sure if I've been correctly utilizing the MVC model.
For example, assume a database of financial transactions (order number, order items, amount, customer info, etc.). Now, assume there is a function to process a .csv file, and return it as an array, to be inserted into the database of transactions.
I've placed my .csv parse function in my Controller, then the controller passes the parsed information to a function in the Model to be inserted. However, strictly speaking, should the .csv parsing function be included in the Model instead?
EDIT: For clarity's sake, I specifically am using CodeIgniter, however the question does pertain to MVC structure in general.
The internet is full of discussion about what is true MVC. This answer is from the perspective of the CodeIgniter (CI) implementation of MVC. Read the official line here.
As it says on the linked page "CodeIgniter has a fairly loose approach to MVC...". Which, IMO, means there aren't any truly wrong ways to do things. That said, the MVC pattern is a pretty good way to achieve Separation of Concerns (SoC) (defined here). CI will allow you to follow the MVC pattern while, as the linked documentation page says, "...enabling you to work in a way that makes the most sense to you."
Models need not be restricted to database functions. (Though if that makes sense to you, then by all means, do it.) Many CI developers put all kinds of "business logic" in Models. Often this logic could just as easily reside in a custom library. I've often had cases where that "business logic" is so trivial it makes perfect sense to have it in a Controller. So, strictly speaking - there really isn't any strictly speaking.
In your case, and as one of the comments suggests, it might make sense to put the CSV functionality into a library (a.k.a. service). That makes it easy to use in multiple places - either Controller or Model.
Ultimately you want to keep any given block of code relevant to, and only to, the task at hand. Hopefully this can be done in a way that keeps the code DRY (Don't Repeat Yourself). It's up to you to determine how to achieve the desired end result.
You get to decide what the terms Model, View, and Controller mean.
As a general rule MVC is popular because it supports separation of concerns, which is a core tenet of SOLID programming. Speaking generically (different flavors support/ recommend different implementations), your model holds your data (and often metadata for how to validate or parse), your view renders your data, and your controller manages the flow of your data (this is also usually where security and validation occur).
In most systems, the Single Responsibility Principle would suggest that while business logic must occur at the controller level, it shouldn't actually occur in the controller class. Typically, business logic is done in a service, usually injected into the controller. The controller invokes the service with data from the model, gets a result that goes into the model (or a different model), and invokes the view to render it.
So in answer to your question, following "best practices" (and I'll put that in quotes because there's a lot of opinions out there and it's not a black and white proposition), your controller should not be processing and parsing data, and neither should your model; it should be invoking the service that processes and parses the data, then returning the results of aforementioned invocation.
Now... is it necessary to do that in a service? No. You may find it more appropriate, given the size and complexity of your application (i.e. small and not requiring regular maintenance and updates) to take some shortcuts and put the business logic into the controller or the model; it's not like it won't work. If you are following or intend to follow the intent of the Separation of Concerns and SOLID principles, however (and it's a good idea on larger, more complex projects), it's best to refactor that out.
Back to the old concept of decomposing the project logic as Models and Business Logic and the Data Access Layer.
Models was the very thin layer to represent the objects
Business Logic layer was for validations and calling the methods and for processing the data
Data Access Layer for connecting the database and to provide the OR relation
in the MVC, and taking asp.net/tutorials as reference:
Models : to store all the object structure
View: is like an engine to display the data was sent from the controller ( you can think about the view as the xsl file of the xml which is models in this case)
Controller: the place where you call the methods and to execute the processes.
usually you can extend the models to support the validations
finally, in my opinion and based on my experience, most of the sensitive processes that take some execution time, I code it on the sql server side for better performance, and easy to update the procedures in case if any rule was injected or some adjustments was required, all mentioned can be done without rebuilding your application.
I hope my answer gives you some hints and to help you
If your CSV processing is used in more than one place, you can use a CI library to store the processing function. Or you can create a CSV model to store the processing function. That is up to you. I would initially code this in the controller, then if needed again elsewhere, that is when I would factor it out into a library.
Traditionally, models interact with the database, controllers deal with the incoming request, how to process it, what view to respond with. That leaves a layer of business logic (for instance your CSV processing) which I would put in a library, but many would put in its own model.
There is no hard rule about this. MVC, however it was initially proposed, is a loose term interpreted differently in different environments.
Personally, with CI, I use thin controllers, fat models that also contain business logic, and processing logic like CSV parsing I would put in a library, for ease of reuse between projects.

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!

What are the main advantages of MVC pattern over the old fashioned 3-layer pattern

I am contemplating about using an MVC pattern in my new project and I can clearly see the main advantage of being able to put the data layer (the model) a little closer to the presentation layer (the view), which will allow a little increase in application speed. But apart from performance stand point are there any other advantages of MVC over the view-logic-data layered type pattern?
EDIT:
For those who's interested I just uploaded a sample PHP code that I created to test the use of MVC. I purposly omitted all the security checks to make the code a little easier to read. Please don't critisize it too much, because I know it could be a lot more refined and advanced, but nevertheless - it works!!! I will welcome questions and suggestions: Here is the link: http://www.sourcecodester.com/sites/default/files/download/techexpert/test_mvc.zip
The separation of concerns that's quoted as being an advantage of MVC is actually also an advance of a 3-layer/3-tier system. There too, the business logic is independent and can be used from different presentation tiers.
A main difference is that in classic MVC the model can have a reference back to the view. This means when data is updated the model can push this data back to possibly multiple views. The prime example is a desktop application where data is visualized in multiple ways. This can be as simple as a table and graph. A change in the table (which is a change in one view) is first pushed via the controller to the model, which then pushes it back to the graph (the other view). The graph then updates itself.
Since desktop development is on the decline, a lot of programmers have only come in touch with MVC in some web variant, e.g. via JSF in Java EE.
In those cases the model almost never has a reference to the view. This is because the web is mainly request/response based and after a request has been served, the server cannot send additional information. I.e. an update pushed from the model to the client would be meaningless. With reverse ajax/comet this is changing, but many web based MVC frameworks still don't fully utilize this.
Thus, in the case of web based MVC, the typical "triangle" between M, V and C is less there and that MVC variant is actually closer to an n-tier model than 'true' MVC is.
Also note that some web MVC frameworks have an intermediate plumbing part between M, V and C called a backing bean (Java/JSF) or code behind (ASP.NET). In JSF the controller is provided by the framework, and the view often doesn't bind directly to the model but uses this backing bean as an intermediary. The backing bean is very slim and basically just pre-fetches data from the model one way and translates model specific messages (e.g. exceptions) into view specific messages (e.g. some human readable text).
Beside
code reuse,
separating of concerns,
less coupling between the layers,
already mentioned by #bakoyaro and #arjan
i think that MVC is better than 3-tier when combined with the "convention over configuration" pattern. (i.e. "ruby on rails" or Microsofts "MVC for asp.net").
In my opinion this combination leads to to better and easier code maintanance.
In the first place it makes learning the mvc-framework a bit more difficuilt since you have to learn the conventions (a la controllers go into the controllers folder and must be named xxxxxcontroller)
But after you learned the conventions it is easier to maintain your own and foreign code.
Forget increasing application speed by moving to MVC. I have found the biggest benefit to be ease of code reuse. Once you move to MVC, there are no dependencies on the presentation of your data or the storage of the actual data.
For example you could write a servlet that served up .jsp pages as your presentation layer one day, and the next day write a web service as another presentation layer to your existing Model and Controller. Like wise if you want or need to switch your DBMS. Since accessing the Model is completely separate from everything else, you would just need to re-write just your data access objects to return the data in a way your Controller can handle it.
By separating concerns into 3 distinct pieces, you also facilitate true unit testing. Your Presentation layer can be tested free of the Model or Controller, and vice-a-versa.
On a side note, I've often felt that the MVC abbreviation was inaccurate. Whenever I see it I think of it as View->Controller->Model. The presentation layer will never have DAO code in it, and the model will never have presentation logic in it. The Controller is forced to act as a go-between.
Where 3-tier separates presentation from business and data access, MVC is a presentation layer pattern which further separates Model (data) from View (screen) and Controller (input).
There is no choosing MVC over 3-tier/3-layered. Use them both.

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.

Simple MVC for Java EE Web Applications?

One of the goals of the MVC approach to web development is to separate out the model, view, controller.
Lets say in a Java EE Struts like environment, you associate the Struts Action with the controller, a Java bean with the model, and JSP and/or ActionForm with the View.
My question, where do you tend to perform any logic to populate data on the JSP. It seems bad practice to put any kind of logic or processing in the view ActionForm and very bad to put any kind of logic in the JSP.
Do you include a "Manager" class to manipulate the data in the View Form before it is display ed to the user.
Here is one simple example. You take First Name, Last Name out of the database and then you need to pretty the format (convert all upper case string to Mixed case). Would the logic to manipulate that string before it gets to the JSP view, add that logic in a manager class?
If it's logic that is only concerned with the view (in your example, making the data look "pretty"), then I would put it in the View. If, however, you would be later saving the modified data, then it should be in the business layer. In general, though, I tend to keep a layer between the View and the Control (your Manager class) that is only concerned with display issues and high level validation of input, but not complex business rules (ensure that very bad data never reaches the business tier).
This very much depends on what framework you're using. I think this kind of thing should be done in the view, but exactly how you would go about that will vary.
If you're using a JSP it might make sense to write a custom tag library to do what you want - so it's separate from the actual HTML but still within the 'view'.
So, you would have something like:
<td><mytag:mixedCase value="${user.firstname}" /></td>
Etc.
For simple presentation concerns such as uppercasing a string, I would put it in the JSP. For more complex business logic, I would put it in the model class. You don't want to be cluttering your controllers with business logic. Another advantage of putting it in the model is that it can be unit tested.

Resources