Is there a downside to validating data through a static method of the Model in an MVP setting? - validation

I was recently reading about MVP, and at the end of the post the author starts to talk about Validation of Data. He mentions
I favour a single isValid() routine in the view.
...
An alternative approach, which is more in-line with the pattern, is to include this method in the interface and for the presenter to call this method (view.isValid()) before attempting to make changes to the model.
I don't think the validation should be handled in the View because it exposes more about the Model than the View should know, especially since we're trying to keep the View and the Model as separate as possible. Plus that method becomes redundant when you have multiple views referencing the same Model (e.g. a quick summary view vs. a more detailed view).
The Presenter has the most opportunity to validate the data, seeing as it is the bridge between the Model and View. I do like the "alternative approach", but I still don't like how it's using view.isValid. Plus I'm still not entirely sure if one presenter controls one view, or multiple view (a question for another time).
But one idea that did occur to me is to use a static isValid() method from the Model. You would call it in the Presenter, and the Presenter would pass all the relevant information from the View to the method. The method returns some form of valid or not-valid, maybe even specific enough to say which pieces of information aren't valid. To me this keeps all information relevant to the Model, within the Model, and accessible to Presenter, while keeping the View blissfully unaware of the Model.
Are there any shortcomings to this idea that other Validation practices solve, or is there any glaring downside to this method of Validation?

Related

What's the controller in MVC pattern and why does it exist?

While working with Unity, I realized that separating Model and View would make my code more readable and straightforward. Constructing the whole model, all I had to do is just create some UI and bind it to Model.
But I still don't understand what 'Controller' is, and why does it exist. I don't think I had trouble when I directly bound View to Model, not through Controller.
So the question is if we can bind View to Model directly, why do we need Controller? What's the benefit of having Controller between Model and View?
At the highest level the Controller is the link between the View (displaying the UI/UX) and the Model (creating and managing your database and its tables).
True, it is possible to write code without any Controller usage but your Views will quickly get very cluttered and each file will be full of logic that is much more nicely stored somewhere else hint hint.
The Controller (and Model and some other places such as helpers) is thus the perfect place to sort out all the back-end code so that all you need to do is send a single field or object to your View to display.
An example is somewhat painful because by its nature the Controller is where you go to sort out your code as things get more complicated but this is a great article to get you on the right track! HTH
https://www.toptal.com/unity-unity3d/unity-with-mvc-how-to-level-up-your-game-development
I don't have years of experience, but in my understanding controllers provide a bridge across view and models. While view contain the pretty part and models contain useful parts the controller do the calls of functions passing values from database to view or inputs to model. That provide a way to avoid lots of injection like class A calling class B, calling class C, etc.
You can put rule business in controllers or in view, but thats not the expected in MVC architecture. The first important thing (for me) in software programming is readability, whats MVC provide.
if you've interest, search for other architectures like MVVM, to compare then.

Is Model-Glue's model in Coldfusion the same as the model in other MVC frameworks?

If you follow the quickstart guide provided by the official Model-Glue docs, found here:
http://docs.model-glue.com/wiki/QuickStart/2%3AModellingourApplication#Quickstart2:ModelingourApplication
It will seem like the "model" is a class that performs an application operation. In this example, they created a Translator class that will translate a phrase into Pig Latin. It's easy to infer from here that the program logic should also be "models", such as database operation classes and HTML helpers.
However, I recently received an answer for a question I asked here about MVC:
Using MVC, how do I design the view so that it does not require knowledge of the variables being set by the controller?
In one of the answers, it was mentioned that the "model" in MVC should be an object that the controller populates with data, which is then passed to the view, and the view uses it as a strongly-typed object to render the data. This means that, for the Model-Glue example provided above, there should've been a translator controller, a translator view, a PigLatinTranslator class, and a Translation model that looks like this:
component Translation
{
var TranslatedPhrase = "";
}
This controller will use it like this:
component TranslatorController
{
public function Translate(string phrase)
{
var translator = new PigLatinTranslator();
var translation = new Translation();
translation.TranslatedPhrase = translator.Translate(phrase);
event.setValue("translation", translation);
}
}
And the view will render it like this:
<p>Your translated phrase was: #event.getValue("translation").TranslatedPhrase#</p>
In this case, the PigLatinTranslator is merely a class that resides somewhere, and cannot be considered a model, controller, or a view.
My question is, is ColdFusion Model-Glue's model different than a MVC model? Or is the quickstart guide they provided a poor example of MVC, and the code I listed above the correct way of doing it? Or am I completely off course on all of this?
I think perhaps you're getting bogged down in the specifics of implementation.
My understanding of (general) MVC is as follows:
some work is needing to be done
the controller defines how that work is done, and how it is presented
the controller [does something] that ultimately invokes model processing to take place
the model processes handle all data processing: getting data from [somewhere], applying business logic, then putting the results [somewhere]
the controller then [does something] that ultimately invokes view processing to take place, and avails the view processing system of the data from the model
the view processes grab the data they're expecting and presents that data some how.
That's purposely very abstract.
I think the example in the MG docs implement this appropriately, although the example is pretty contrived. The controller calls the model which processes the data (an input is converted into an output), and then sets the result. The controller then calls the view which takes the data and displays it.
I disagree with the premise of this question "Using MVC, how do I design the view so that it does not require knowledge of the variables being set by the controller?" The view should not care where the data comes from, it should just know what data it needs, and grab it from [somewhere]. There does need to be a convention in the system somewhere that the model puts the data to be used somewhere, and the view gets the data it needs from somewhere (otherwise how would it possibly work?); the decoupling is that model just puts the data where it's been told, and the view just gets the data out from where it's been told. The controller (or the convention of the MVC system in use) dictates how that is implemented. I don't think MG is breaking any principles of MVC in the way it handles this.
As far as this statement goes "In this case, the PigLatinTranslator is merely a class that resides somewhere, and cannot be considered a model, controller, or a view." Well... yeah... all a model IS is some code. So PigLatinTranslator.cfc models the business logic here.
And this one: "In one of the answers, it was mentioned that the "model" in MVC should be an object that the controller populates with data, which is then passed to the view"... I don't think that is correct. The controller just wrangles which models and which views need to be called to fulfil the requirement, and possible interchanges data between them (although this could be done by convention, too). The controller doesn't do data processing; it decides which data processing needs to be done.
Lastly, I don't think the "strongly-typed" commentary is relevant or an apporpriate consideration in a CF environment because CF is not strongly typed. That is a platform-specific consideration, and nothing to do with MVC principles.
I think one of the common confusions around MVC is that there are multiple Views, multiple Controllers but only one Model. cfWheels has a "model" object for each persistent domain object which I think is very confusing - but of course cfWheels is drawn from Ruby on Rails which also uses "model" in that context.
In general, in MVC, "The Model" represents your business data and logic as a whole. The Model is made up of a number of domain objects (which are typically persistent) and a number of service objects (which exist to orchestrate operations across multiple domain objects). In real world applications, you typically have a data layer that manages persistence of domain objects - which may be partitioned in a number of ways.
It may also help to think of the input data that the view needs as it's "API" and it is the controller's job to satisfy that API by providing compatible data. Think of it more that the controller needs to know what type of data will satisfy the view rather than the other way around.

In MVC, why should the model notify the views, and why should the view have the model?

In my world, the model notifies only the controllers subscribed to the model's event. Then the controller tells the view what to do, for example adding a new row to a list.
The same with the view: the view notifies the controller subscribed to the view's event. Then the controller modifies the model as needed, for example setting the name of a person, and call the Save() method on the model.
Okay, I know I'm wrong, I don't think every article about MVC is wrong because I'm thinking in another way. The point in MVC is to seperate the UI from the data model. How does this come true when the view and the model reach each other? Why should they do so?
Thanks for Your answer!
Model-View-Controller is seen different ways by many people, but I like to think of it as a combination of several other patterns rather than as a single pattern. This may come originally from this note
The connection of the view to the model is an Observer Pattern, with the model notifying the view when it has changed. There's no need for the controller to be involved in this.
I completely agree with you on this one.
For every project i work on, i try to enforce this:
View --> Controller --> Model
So that every action or event in the view call a specific controller method. This controller method will do his job (validate, call other service, etc) then if persistence is needed, it will the call the associated ModelService to persist the data.
in my world, a view component should never call a ModelService without going thru a controller.
But that's just me ;-) (and almost 100% of the good architect and designers i worked with)
I like to think of the model as a transparent thing, adhering to some sort of scheme. Very easy to "read" by a view. I never make my views programmatic, in the sense that you can call all sorts of methods on it. Usually my view is HTML, my model has methods but is also capable of presenting itself as a plain data structure, and there is an intermediate: in the form of a template engine.
But, there are lots of variants for MVC. I don't think there are 2 developers who would exactly, exactly, agree on what MVC actually is. MVC is -in my view - a pattern to help you. It is not a law that is trying to hold your creativity back by exactly defining up to the last bit what you have to do.

Zend Framework / MVC: What type of objects to push to the View?

Hey guys - here's a question on Zend Framework or better on MVC in general:
I am asking myself for a quiet a long time now, if it is a good idea to push business objects (User, Team, etc.) to my views or if it would be better just to push dump data containers such as arrays to the view for rendering.
When pushing business objects to my view I have a much tighter coupling between the views and my domain model, however, the view could easily do things like foreach($this->team->getUsers() as $user) { ... } which I personally find very handy.
Providing domain model data in dumb arrays to me looks more robust and flexbile but with the costs of that the view cannot operate on real objects and therefore cannot access related data using object's method.
How do you guys handle that?
Thanks much,
Michael
It's better to make your View access a Domain Model object in an object-oriented manner, instead of using the Controller to convert Model data into plain scalars and arrays.
This helps to keep the Controller from growing too fat. See the Anemic Domain Model anti-pattern. The Controller only needs to know what Model to instantiate, passes the request inputs to that Model, and then injects the Model into the View script and renders. Keep in mind that a Domain Model is not a data-access class.
You can also write View Helpers to encapsulate a generic rendering of a Domain Model object, so you can re-use it in multiple View scripts.
Your View should accesses the Domain Model only in a read-only manner. View scripts should not try to effect changes to the Domain Model.
You can also design your Domain Model to implement ArrayObject or other SPL type(s), as needed to make OO usage easy in the View script.
It's true, a large driving motivation of MVC and OO design in general is decoupling. We want to allow each layer to remain unchanged as the other layer(s) are modified. Only through their public APIs do the layers interact.
The ViewModel is one solution to abstract the Model so that the View doesn't need to change. The one I tend to use is Domain Model, which abstracts the details of table design, etc. and supplies an API that is more focused on the business rather than the data access. So if your underlying tables change, the View doesn't have to know about it.
I would expect that if there's a change to the Domain Model, for instance it needs to supply a new type of attribute, then it's likely that your View is changing anyway, to show that new attribute in the UI.
Which technique you choose to decouple one layer from the others depends on what types of changes you expect to be most frequent, and whether these changes will be truly independent changes, or if they will require changes to multiple layers anyway.
The "standard" approach would be to completely prepare the model in the controller (e.g. fetch all teams, including users) and then send that to the View for presentation, but you are not bound by that. The data structures can be whatever you want it to be: Array, ArrayObject or custom Classes - anything you deem appropriate.
I dont use Zend framework, so this is in repsonse to the general MVC Have a look at the ViewModel pattern.
http://www.lostechies.com/blogs/jimmy_bogard/archive/2009/06/29/how-we-do-mvc-view-models.aspx
I'm comming from a .Net MVC point of view but I believe the concepts will the same.
I will do all my view rendering in the controller bascially like below
model only output dataset/objects (this should contain the most code)
controller assign view and add necessary HTML and make use of models
view only contains placeholder and other presentation stuff and maybe ajax call
So my team can work on each part without interrupting each other, this also add some information security to the project i.e no one can retrieve all the working code they only communicate by variables/object spec.

Can any processing be done on the model? [MVC]

I've decided to make a big push towards MVC for all new sites I make. I have a question about whether or not you can have any processing on the model level.
The case that brought up this question is a video site. I have a Video class (model) and one of the things I need to do when a user views the video I need the view to be logged in the database. I'm not sure if I need to add a query in the controller or if I can add a addView method in the Video class.
The basic underlying question for me is what kind of methods am I limited to in the models? Can it be anything or does it have to be only accessor (a.k.a getValue/setValue) methods?
Ruby on Rails has the motto skinny controller, fat model. This doesn't apply to just Rails and should be practiced with any mvc framework.
I think your model is exactly the place to handle this. Now, your model is necessarily composed of just your entity classes. Your model, in my opinion, would include your entities as well as any business logic that you need to implement. Your controller should just be handling I/O for the view, invoking model methods to accomplish the actions invoked by the user via the user interface (view).
Here how I would do this. It should be valid in pretty much any language.
The View would initiate a method call to the controller's OnView() method, then display whatever the controller spits back to it (in a controlled way, of course... I'm thinking your view is going to contain a video player component, so you're going to get a video of some kind back from the controller)
In your controller, have a method OnView() that does 3 things: instantiate the Video object (i.e. uses your data layer to get a model object), call the updateViewCount() method on the Video object, and display the video (by returning the Video object to the View, presumably).
The Video model object contains data representing your video and any houskeeping stuff you need, which includes updateViewCount(). The justification for this is that a Video has a view count (aggregation). If "view count" needs to be a complex object instead of just an integer, so be it. Your data layer that creates Video objects from their primitive representation on disk (database?) will also be responsible for loading and creating the corresponding view count object as part of the creation of the Video.
So, that's my $0.02. You can see that I've created a 4th thing (the first three being Model, View, and Controller) that is the data layer. I don't like Model objects loading and saving themselves because then they have to know about your database. I don't like Controllers doing the loading and saving directly because it will result in duplicated code across Controllers. Thus, a separate data layer that should only be directly accessed by Controllers.
As a final note, here's how I look at views: everything the user does, and everything the user sees, should go through the view. If there's a button on the screen that says "play", it shouldn't directly call a controller method (in many languages, there's no danger of doing this, but some, such as PHP, could potentially allow this). Now, the view's "play" method would just turn around and call the appropriate method on the controller (which in the example is OnView), and do nothing else, but that layer is conceptually important even though it's functionally irrelevant. Likewise, in most situations I'd expect your view to play a video stream, so the data returned by the controller to the view would be a stream in the format the view wants, which might not necessarily be your exact Model object (and adding that extra layer of decoupling may be advisable even if you can use the Video object directly). This means that I might actually make my OnView method take a parameter indicating what video format I want to get back, or perhaps create separate view methods on the controller for each format, etc.
Long winded enough for ya? :D I anticipate a few flames from the Ruby developers, who seem to have a slightly different (though not incompatible) idea of MVC.
Since you can use whatever model code you want with MVC (not just limited to LINQ) the short answer is yes. What should be done in the model is perhaps a better question. To my taste, I would add a ViewCount property (which probably maps to a column in the Video table, unless you are tracking per user in which case it would be in the UserVideo table). Then from the controller you can increment the value of this property.
With MVC, people seem to be struggling with fitting four layers into three.
The MVC paradigm does not properly address the data storage. And that's the "fourth layer". The Model has the the processing; but since it also addresses the data, programmers put SQL in there, too. Wrong. Make a data abstraction layer which is the only place that should talk to back-end storage. MVC should be DMVC.
Keep in mind, there are many variations on MVC and no real "right way" to do things. Ultimately, how you design your classes comes down to personal preference. However, since you asked for design advice, here are my two cents:
Business logic belongs in the controller. Keep it out of the model and view.
Out of the many variations on the MVC pattern, the passive view style seems to be the easiest to test. In the passive view, your classes are designed as follows:
Your controller is "smart: it makes changes to the database, updates the model, and syncronizes the view with the model. Apart from a reference to the model and view, the controller should hold as little stateful information as possible.
The model is "stupid", meaning it only holds the state of the view and no additional business logic. Models should not hold a reference to either the view or controller.
The view is "stupid", meaning it only copies information from the model to the UI, and it invokes event handlers which are handled by the controller. The view should contain no additional business logic. Views should not hold a reference to the controller or model.
If you're an MVC purist, then it would not make sense for the model to update itself or the database since those responsibilities belong to the controller, so it would not be appropriate to create an addView method to your Video class.

Resources