Is Data Annotations validation a good practice? - validation

Is using data annotations validation like in MVC really a good practice? wouldn't it pollute my POCO based domain model? Should I care about it or it is just another slip for Microsoft that I should overlook?

I wouldn't exactly say pollute. I mean let's be honest.. Data Annotations barely take up any space at all, and they're super easy to find since they are decorated over their respected properties.
But in terms of separation of concerns.. the models/classes purpose is to perform business logic. Most, if not all, of the stock data annotations deal with business logic. However, this can be subjective/opinion based because some developers perform business logic in the controller and/or the view.. depending on the situation.. so it can vary.
So.. in my opinion I think data annotations are very good practice when it comes to the MVC world. The more that a developer can separate the responsibilities of the Model, View, and Controller without intertwining them.. the more maintainable the code will be in the future.
I hope this helps.

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.

Is the MVC-pattern a pure presentation-tier pattern?

Kind of a special question today :)
I just had a test at my technical university where I was told that I am wrong.
So I like to know from you folks(I believe you more than my teachers):
Is the MVC-pattern implemented at the presentation-layer only?
Or is the Model-part of the pattern in the Business/DataAccess-layer implemented.
My teacher said, it's not possible that a pattern can span more than one tier.
But I think it's an an enterprise-architecture-pattern and therefore can span multiple tiers.
How wrong am I? :)
You're wrong... for the class. In class, what teacher/book says goes.
Outside class, I agree with you 100%.
Your teacher is right, the "model" merely represents data that is to be presented. For example, the data that makes up a web page.
The data itself will ultimately come from the business layer, but the model should be restricted to the presentation layer. It's the model of your presentation.
For example, you might retrieve data as datasets, and use the datasets to build page-specific models.
I would think MVC does go deeper than presentation tier for the simple reason that supplying the model does require other tiers to do "something".
Besides if we think of model as some representation of Domain concepts (see DDD) - then we are already talking about going outside of Presentation tier.

What is the usage of Model in MVC? Is it actually useful?

I'm new in this, so bear with me. I've been using one MVC framework in a couple of projects lately, and after a while, I'm disillusioned in the perceived usefulness of the 'Model' in MVC.
I get the usefulness of Controllers and Views, I know that separation between presentation and logic is important to make the code more maintainable in the future, although not necessarily faster or more robust.
If all logic should be placed inside the controller in the first place, I don't see any use for Model, especially the Active-Record. We already have a language that is so robust and easy to use to communicate with the database, am I right? It's called SQL. For me when models are implemented like active-record, it's usefulness depends on whether or not you want your app to fit in multiple databases.
So what I'm asking is, if you're only using one database, why bother with Models and Active-Records? Why don't just use SQL? Why the extra layer of complexity? Do you guys have any case studies/real-life stories where models actually can do things better than just using the database class and SQL-away?
Again, I'm sorry if I seem to be so ignorant, but I really don't know why Models are important. Thanks for answering.
First, you are assuming that a model layer necessarily uses some kind of ORM, in order to abstract SQL away. This is not true: you may create a model layer which is loosely-coupled from the Controller layer but tightly-coupled to a particular DBMS, and so avoid using a full-featured ORM.
There are some ORM libraries, like Hibernate (Java), NHibernate (.NET), Doctrine (PHP) or ActiveRecord-Rails (Ruby) that really can generate all actual SQL statements for you; but if you think ORM is unnecessary, and you want to define all SQL statements by hand, don't use them.
Still, IMHO this does NOT mean you should just place all you DB related logic inside the controller layer. This is called the "fat controller" approach, and it is a road that leads, many times, to bloated, unmaintainable code. You could use it for simple CRUD projects, but anything beyond that will demand the existence of a real "Model".
You seem to care about MVC. Please, read also something about TDD. A wise man once said "legacy code is code without tests". When you learn that automated unit tests are as important as the "real" code, you will understand why there are so many layers in an enterprise application, and why your Model layer should be separate from the Controller. A block of code that tries to do everything (presentation, business logic, data persistence) simply cannot be easily tested (nor debugged by the way).
Edit
"Model" is a little bit fuzzy term. Depending from where you look at, it can mean something slightly different. For instance, PHP e Ruby programmers frequently use it as a synonym to an Active Record, which is not accurate. Some other developers seem to believe that a "model" is just some kind of DTO, which is also not right.
I rather use the definition of model as seen in Wikipedia:
The central component of MVC, the model, captures the application's behavior in terms of its problem domain, independent of the user interface. The model directly manages the application's data, logic and rules.
So the Model is the biggest, most important layer in most MVC applications. That's why it is usually divided in sub-layers: Domain, Service, Data Access and so on. The Model is usually exposed through the Domain, because it's there where you'll find the methods that your controller will call. But the Data Access layer belongs to the "Model" too. Anything that is related to data persistence and business logic belongs to it.
In most real-life situations, data that comes from the user doesn't go straight into the database.
It must often be validated, filtered, or transformed.
The role of the model layer is usually to make sure that data arrives properly into the backend store (usually the database) by performing these operations, which should not be the responsibility of the controller (skinny controller, fat model), and not the responsibility of the database engine itself.
In other words, the Model layer is responsible - or `knows' - how the data should be handled.
Most modern MVC frameworks provide ways to specify contracts over the data validity requirements, such as Rails.
Here's an example from http://biodegradablegeek.com/2008/02/introduction-to-validations-validation-error-handling-in-rails/:
class Cat
validates_inclusion_of :sex, :in => %w(M F), :message => 'must be M or F'
validates_inclusion_of :vaccinated, :in => [true,false]
validates_inclusion_of :fiv, :in => [true,false]
validates_inclusion_of :age, :within => 1..30
validates_each :weight do |record, attr, value|
record.errors.add attr, 'should be a minimum of 1 pound' if value and value /^[01][0-9]\/[0-9]{2}\/[0-9]{4}$/
validates_length_of :comment, :allow_blank => true, :allow_nil => true, :maximum => 500
end
Here, several of the data validity requirements cannot be handled by the database, and should not be handled in controllers, because any modification in those requirements might break the code in several places.
Therefore, the model is the best place to make sure data is coherent for your domain.
There's a lot more to be said about it, but I felt like tackling a point that seems important to me, motivated by practical experience :)
It's not an ignorant question at all! Just the fact that you're asking it instead of simply ignoring the whole MVC theory and doing as you please is nice. :-)
To answer your question: conceptually, Models simply provide a nice abstraction for your data. Instead of thinking in terms of "how do I write this inner join to get all the fields I need", models enable you to think in terms of "how are my application's objects related to each other, how do they interact and how can I get the data I need from them".
In the same way that Views and Controllers help you seperate presentation from logic, Models help you seperate the application's logic (from a user's perspective, anyway) from the gritty details as to where your data actually comes from and how it's represented internally.
To give a more specific example (if not completely realistic): in theory, you could write your whole application in a way you fetched all the data through SQL queries. But later you realized you wanted to use some noSQL (CouchDB, etc) engine because you needed horizontal scaling.
With models (and a framework that can use both types of storage, of course :-)) you wouldn't have to worry about the details, as all your important data is already represented in a generic manner through your models and both views and controllers can act upon that representation.
Without them, you'd probably have to rewrite a large chunk of code just to adapt your data fetching to the new backend.
And that's just on the boring storage part. With pure SQL, it's much harder to define the interactions between your application's objects (i.e. the business logic) because you just won't do that in SQL (probably, anyway).
It's not a perfect explanation (far from it), but I hope it helps.
The models should contain all your logic. The controller is only responsible with logic related to user interaction. All the domain-related functionality (what's known as "business logic") should be placed in the model and decoupled from controller code. Like this you can achieve a better separation of concerns and code reusability.
For example, let's say you are writing an application to let users enter information about themselfs and receive diet recomandations.
One the one hand, you would put code related to transforming user provided data into a list of diet recomandations in the model part. This includes database access, but also any calculations , algorithms and processing related to the problem in question (the problem domain).
On the other hand, you put the code to log the users in, show a form, gather the form data, validate it, in the controller. This way for instance you could later add an api to your app (which uses different code for authentication, getting data from the user, validation etc.) and reuse the code to generate the results (from the model).
This is just an example of what the model is good for.
I always relate Model to data irrespective of where it is present or how it is represented. In MVC V displays data and C handles change. Even if you have all the data to be presented on the screen in a HashMap inside your controller; that HashMap will be called the Model.

Is fetching HTML directly from Model (MVC) a good idea?

Looking at examples and tutorials for some MVC libraries for web development on the Internet, I found that many of them construct HTML directly in the code of Model class and then Controller just sends it to the View which just displays it. While this makes Controller and View very simple and clean, I feel it is a wrong approach. IMHO, Model should just retrieve data, without having any representation logic in it. Controller should pass this data to the View, and View would contain the code that iterates through it and generates final HTML.
Is my thinking correct, or am I missing some important point here?
Presentation logic is shared between the view (most of it) and controller. The model should not concern itself with presentation logic.
If it does, you don't have separation of concerns. This isn't inherently a bad thing, but you miss the advantages of having presentation and business logic separated. So no, it's not a good idea.
This being said, there are elements of presentation logic that may get to the model. Think of a cms. Idealy you would have all the data marked up, let's say xml, on which you would apply a template to deliver it. But the data, and the template are kept in the model. So what is presentation, and what is business here?
There are gray areas, but most of the times is easy to separate presentation and business logic.
Your thinking is absolutely correct. If you want a clean separations of concerns it is best to have the View generate HTML from Model. In some cases html helpers could be used.
Is fetching HTML directly from Model (MVC) a good idea?
My gut instinct would say no. Breaks the concept of separation of concerns.

MVC Architecture. Whats in a model?

I am new to MVC but I can already see its benefits and advantages. However, I have a (probably easy to answer) design question:
I have been thinking about models and debating the proper way to structure them. The way I see it there are a few options:
1) Models and table structure have a 1 to 1 relationship...meaning that pretty much for every table there is a corresponding model. The model class has attributes corresponding to the table columns and has whatever methods that are needed (like getters and setters) to manipulate data in the table in whatever way is necessary. This seems like the generic option and I guess I would then have the controller call the models as necessary to perform whatever business function is necessary.
2) Models are tied more closely to the operation of the business logic rather than the data: so for example if on the front end a deletion of a certain object affects multiple tables, the model then 'models' this behavior and interacts with several tables and performs the necessary function. The controller then simply needs to call a single model for whatever business behavior is desired. This is less generic since the models are much more tightly coupled..but seems quicker to implement.
3) Something in between the first 2 options. Or maybe I am completely missing the point.
Hopefully this makes sense! If I am not totally missing the point, I am inclined to think that option (1) is better. Any idea?
Edit: Not that it should matter, but I plan on using Codeigniter PHP MVC framework.
Both are valid implementations, and, depending on your needs, can work well.
Your #1 is essentially describing the Active Record pattern, which is used by SubSonic, Castle, and lots of other ORM implementations.
Your #2 is essentially describing the Entity Framework/Hibernate/LightSpeed approach, where you are dealing with objects that are more conceptually related to your domain rather than to tables. Instead of your objects containing foreign key ID properties, they actually contain the other domain object references, which are then instantiated in an on-access basis.
Both ways are great. The Active Record approach is usually more intuitive for beginners and has potentially less pitfalls. EF-style can save a lot of base-level coding and dealing with FK's directly in code.
Edit: To be clear, what you describe in both situations is data access layer related, rather then strictly model related. However in reality you're pretty close, as most models tend to simply represent one or more of these types of objects.
All of the above.
The approach you use depends on your design philosophy. If you prefer to design your application using business domains and drive that into the database design, then you favor the second approach. If you prefer to build your database first, and then create model classes from the database schema, then you favor the first approach. Both methods are valid ways to build software.
Number 1 is the way to go. Option 2 is really the controller's job. For example, the controller then takes the models and performs actions on them, and passes the results to the view.
Think of it this way:
Model = your data
Controller = business logic
View = display of data and actions
This is highly simplistic, but it's how I picture it in my mind when I go to design a system.
Think of the database as the Model, the business logic as the Controller, and the UI as the View. That may help. It's an overly simplified approach to things, but it gets the data / behavior separation roughly correct.
I don't think it has to be an either/or situation. Your first point is what would be called a Model, but your 2nd point sounds like a View Model, which is most often a composition of various Models and parts of Models that will be sent to the view. The controller is responsible for doing that composition and potentially decomposition when information is sent back from the View.

Resources