Is data binding fundamentally incompatible with MVC? - model-view-controller

Data binding establishes a direct coupling between the view and the model, thereby bypassing the controller. Fundamentally this breaks with the Model-View Controller architectural pattern, am I right in thinking this? Does this make data binding a "bad thing"?
Edit: As example, angular claims to be a MVC framework, yet one of its main features is data binding.

In my opinion Data Binding can be a valid implementation of the MVC Pattern since the data binding mechanism itself acts as the controller in that case.
For example in the mentioned angular it seems like the $watch function is a shortcut to implement features that are typical Controller responsibilities and features in an MVC-style way.
So in my opinion data binding is an evolution step that implements best practices learned by implementing classic MVC controllers.
UPDATE
But in original pattern sense I would characterize data binding more like MVP or Passive View.
But the differences aren't that sharp in my opinion since it always also depends on your UI technology.

Not necessarily, since you don't have to bind your Model objects to the view.
What I usually do is create simple DTOs (or Presentation Objects) that contain only the data I want to display, and that's what the View layer displays.
In that case, the Controller retains its function as a translator between actions performed on the DTOs and actions on the underlying Model entities.

Actually, when your data is abstracted properly, the act of pushing the content of your models to your UI is a repetitive task that normally lead to some kind of "helpers".
Let's say to push a list of items to a combobox. This is not necessarily part of the controller as you may want to share such functionality. Also pushing the value of the control (to keep it simple, let's say the text of a textbox) is repetitive and bi-directional.
Also here you repeat your self (think of DRY) and do the same thing over and
over again.
That's exactly the point where databinding comes into play. This can take over the tasks that anyway are identical for simple controls (checkbox, textbox, combobox). For grid control and the like it may be specific.
Have a look at mvc & databinding: what's the best approach?. Here I discuss what could be the optimum when using databinding in combination with MVC.

Data Binding does not directly couple the view and model, so it is not a Bad ThingĀ®. It is an integral feature of the MVC architecture, which the GoF Design Patterns book describes succinctly in chapter 1.
MVC decouples views and models by establishing a subscribe/notify protocol between them. A view must ensure that its appearance reflects the state of the model. Whenever the model's data changes, the model notifies views that depend on it. In response, each view gets an opportunity to update itself. This approach lets you attach multiple views to a model to provide different presentations. You can also create new views for a model without rewriting it.
It's a common misconception that MVC is a layered (3-tier) architecture. It is not. The model updates the view(s) directly. But this does not mean the two are coupled! A publish/subscribe design keeps the model and view decoupled.
This more general design is described by the Observer design pattern.

Related

Can the V access the M in MVC?

While using a custom MVC framework I found that the view can actually access data in the model. That was a bit of a surprise because I always thought the V must go through the C. It was something like
//this is completely made up but not far off
serverside foreach(var v in Model.GetSomeList()) {
<div>#v.name</div>
}
Do many MVC frameworks in any programming language allow the view to access anything in the model? When do i choose what should go through the controller and what is ok to access from the view?
Usually that "Model" is really like viewmodel, not the business layer Model object, although it could be the POCO version of the business object. Basically, the view is bound to some poco without any business logic.
Information flow in classical MVC.
Data in MVC should not go from model through controller to view. That is violation of the original concept.
If you read the original definition of MVC design pattern you will notice that Views are meant to request the data from Model. And views know when to do it, because they are observing Model for changes.
Modern interpretations.
In the original concept you were meant to have small MVC triad for each element in the application. In modern interpretation (as per Martin Fowler), the model is not anymore any single object or class. Model is a layer, which contains several groups of objects. Each with a different set of responsibilities.
Also, with the rise of Web there was another problem. You cannot use classical MVC for websites. Theoretically now you could achieve it by keeping an open socket and pushing a notification to the browser every time you changed something in the model layer.
But in practice even a site with 100 concurrent users will start having problems. And you would not use MVC for making just a blog. Using such an approach for even minor social network would be impossible.
And that was not the only divergence from the original concept.
MVC-inspired patterns
Currently, along with classical MVC (which is not even all so classical anymore). There are three major MVC inspired patterns:
Model2 MVC
This is basically same classical MVC patter, but there is not observer relationship between model later and view(s). This pattern is meant to me more web-oriented. Each time you receive a user request, you know that something is gonna change in model layer. Therefore each user request cause view instance to request information from the model layer.
MVP
This pattern, instead replaces controller with a presenter. The presenter request data from model layer and passes it to current view. You can find patterns definition here. It is actually a lot more complex, and I, honestly, do not fully understand it.
In this case the View is passive and will not request any data from model layer.
MVVM
This pattern is closer to MVP hen to classical MVC. In this case the controller-like structure (which actually would be more then a monolith class) request data from model layer and then alters it in such a way as it is expected by the (passive) view.
This pattern is mostly aimed at situation where developer does not have full controller over views or/and model layer. For example, when you are developing some application where model layer is SAP. Or when you have to work with an existing frontend infrastructure.
FYI: what is called "MVVM" in ASP.NET MVC is actually a good Model2 implementation .. what they call "viewmodels" are actually view instances and "views" are just templates that are used by views.
This is common. If you look at the Wikipedia page for MVC, this is what it says for the view:
A view requests from the model the information that it needs to generate an output representation.
MVC is an architectural style, so some people change it as they see fit. From the design intentions of the architecture this particular question is certainly not frowned upon.

What is the advantage of Model-View-Controller (MVC) over Model-View?

Could anyone give an example of why it would be advantageous to use MVC instead of a simpler Model and a View only.
Note: whether it's called MVC or MVP (Model-View-Presenter), I'm talking about the one where the View receives input, then the Controller will respond to the input event by interpreting the input into some action to be done by the Model. When the model changes, the View will update itself by responding to events from the model.
What is disadvantageous of simply letting the Model respond to events in the View and vice versa?
In MVC, if I changed the model in a way that affects the controller then I'll have to do changes in the controller. In Model-View, if I change the Model, I'll have to update the view.
So, it seems like we are introducing complexity by adding the "controller" part?
In MVC, the Model is blind to its environment, the view can be too - passing off (blindly) its events to the controller, which knows more about the view and model. So when all is said and done, the controller is the 'non-reusable' disposable part of the system, since it is the most context aware component.
if I changed the model in a way that affects the controller...
The the model should expose simple CRUD methods in such a way that those using the methods do not have to know anything about the passed update object, nor what really happens inside the model.
This means that the view, IMO, has to do a bit of work by creating the passed record, since Controllers are supposed to be stateless and the view is more persistent. Controllers get triggered and 'kick-in' do their work with a passed object and do not have a state.
The passed data is created by some sort of generic convention.
Let me go even further. Suppose you have a view, a tablegrid, and a control whose enabled property is dependent on item is selected in the grid -- you COULD create a view that handles both those controls and this logic internally, and that would probably be the way to go in such a simplified example.
But the more atomic your views are, the more reusable they become, so you create a view for every, yes every, control. Now you are looking at a situation where views have to know about each other in order to register themselves for the right notification...
This is where the controller steps in, since we want to stick all these dependencies onto him, the long term disposable one. So the controller manages this type of view-to-view notification scheme.
Now your views are ignorant as they can be and independent, thus reusable.
You can code a view without having to know about the system, or the 'business logic' as they like to call it. You can code a model without having to know too much about your goals (though it does help to tweak the model to enable it to return the datasets you have in mind).... but controllers, they are last and you have to have the previous two firmed up before you can wire things together.
Here is another thing to think about -- just as the Model is supposed to abstract-away and provide a generic interface to the underlying implementation of the data it is managing (the client does not know if the data comes from a DB, a file, a program setting, etc) -- the view should also abstract away the control it is using.
So, ultimately this means a view should not (caveat below) have functions/properties that look like this:
public property BackgroundColor{get;set}
Nor
public function ScrollBy(x,y){}
But instead:
public SetProp(string name, object val){}
And
public DoCmd(string name, object val){}
This is a bit contrived, and remember I said ultimately... and you ask why is this a good idea?
With reusability in mind, consider that you may one day want to port things from WinForms to, say, Flex, or simple want to use a new-fangled control library that may not expose the same abilities.
I say 'port' here, but that is really not the goal, we are not concerned with porting THIS particular app, but having the underlying MVC elements generic enough to be carried across to a new flavor -- internally, leaving a consistent and ability-independent external interface intact.
If you didn't do this, then when your new flavor comes along, all your hard references to view properties in the (potentially reusable/refactorable/extendable) controllers have to be mucked with.
This is not to mean that such generic setters and cmds have to be the interface for all your views abilities, but rather they should handle 'edge case' properties as well as the normal props/cmds you can expose in the traditional hard-link way. Think of it as an 'extended properties' handler.
That way, (contrived again), suppose you are building on a framework where your buttons no longer have buttonIcon property. Thats cool because you had the foresight to create a button view interface where buttonIcon is an extended property, and inside the view your conditional code does a no-op now when it receives the set/get.
In summary, I am trying to say that the coding goals of MVC should be to give the Model and View generic interfaces to their underlying components, so when you are coding a Controller you don't have to think to hard about who you are controlling. And while the Controllers are being (seemingly unfairly) set up to be the sacrificial lamb in the long run of re-usability -- this does not mean ALL your controllers are destined for death.
They are hopefully small, since a lot of their 'thinking' has been shoved off into semi-intelligent Models and Views and other controllers (ex: Controller to Sort a Grid or Manipulate a TreeView) -- so being small they can be easily looked at and qualified for reuse in your next project -- or cloned and tweaked to become suitable.
It actually reduces complexity by separating the workflow logic from the domain logic. It also makes it easier to write unit tests and makes your application easier to maintain and extend.
Imagine if you wanted to add a new data type. With the approach above, you would probably duplicate a lot of the workflow logic in the new class as it would be likely to be tightly coupled to the domain logic.
The discipline involved in separating the workflow logic into the controller makes it more likely that you will have fewer dependencies between workflow and domain logic. Adding a new data type would then be more simple, you create the new domain object and see how much of the controller you can reuse, e.g. by inherited from a controller super class.
It would also make it easier to change frameworks in future - the model would probably not change too much and so would be more portable.
Having said that, you might want to look into MVVM depending on what you are using as your presentation layer: Benefits of MVVM over MVC
Advantages of MVC/P (I am talking about Supervising Controller here) over MV include:
You can handle complex data binding code in the controller, if required.
You can test that complex presentation logic without a UI testing framework.
You can also have a graphic designer make your views, and not see your code, and not mess up your code when they fix your views.

How do Gang of Four Design Patterns fit into the MVC paradigm?

I've mulled over Design Patterns for some time now and I am just starting to see how I might actually begin incorporating some of these more deliberately in my development work. However, I am still confused about their treatment of MVC in the beginning of the book and how it relates to the rest of the book.
Most of the frameworks I have worked with - Spring, Yii, ASP.NET, and even Objective-C Cocoa (UIKit) - cater to the MVC paradigm. I get MVC because to me it is a useful way of classifying objects and how they should message or interact with each other. Plus, these frameworks kind of force it upon you even if you are not setting out to think in the MVC way.
I also feel that I understand the premise of Design Patterns: they really don't like subclassing, they love abstract interfaces, and they strive for loose coupling. I can't say I fully understand all of the patterns yet or how they are useful, but I am getting a feel for it.
My question is this: what is the interplay between MVC and design patterns? What were they getting at in the first chapter of the book with the MVC application example? Are certain design patterns just not relevant in the MVC paradigm? I wonder, for example, how the Command pattern is supposed to fit into MVC. It seems incredibly useful, but do we create a CommandModel and CommandController to send to other controllers? Do we just create a Command object as prescribed in the book? Basically, I am wondering if the ideas of MVC and Design Patterns are wholly disjoint and I just don't understand, or if there are some patterns that do not fit into the mold.
My personnal opinion is that MVC is a simplified version of the Observer Pattern which is a simplified version of the Mediator Pattern.
MVC: One Model, One view, the Controler manages the communication between them.
Observer Pattern: One Model, Multiples views ( observers/subscribers ), and the publisher manages the communication
Mediator Pattern: Several different Models, Several views, and the mediator manages the communications between them.
The MVC in the GoF book is for the desktop, it uses the observer pattern to update views. The command example in the GoF book is for an editor.
There are other flavors of MVC where the use of other design patterns may not be obvious:
What is the difference between MVC and MVVM?
Presentation abstraction control
The GoF book says:
...
Taken at face value, this example reflects a design that decouples views from models. But the design is applicable to a more general problem: decoupling objects so that changes to one can affect any number of others without requiring the changed object to know details of the others. This more general design is described by the Observer (page 293) design pattern.
Another feature of MVC is that views can be nested. For example, a control panel of buttons might be implemented as a complex view containing nested button views. The user interface for an object inspector can consist of nested views that may be reused in a debugger. MVC supports nested views with the CompositeView class, a subclass of View. CompositeView objects act just like View objects; a composite view can be used wherever a view can be used, but it also contains and manages nested views.
Again, we could think of this as a design that lets us treat a composite view just like we treat one of its components. But the design is applicable to a more general problem, which occurs whenever we want to group objects and treat the group like an individual object. This more general design is described by the Composite (163) design pattern. It lets you create a class hierarchy in which some subclasses define primitive objects (e.g., Button) and other classes define composite objects (CompositeView) that assemble the primitives into more complex objects.
MVC also lets you change the way a view responds to user input without changing its visual presentation. You might want to change the way it responds to the keyboard, for example, or have it use a pop-up menu instead of command keys. MVC encapsulates the response mechanism in a Controller object. There is a class hierarchy of controllers, making it easy to create a new controller as a variation on an existing one.
A view uses an instance of a Controller subclass to implement a particular response strategy; to implement a different strategy, simply replace the instance with a different kind of controller. It's even possible to change a view's controller at run-time to let the view change the way it responds to user input. For example, a view can be disabled so that it doesn't accept input simply by giving it a controller that ignores input events.
The View-Controller relationship is an example of the Strategy (315) design pattern. A Strategy is an object that represents an algorithm. It's useful when you want to replace the algorithm either statically or dynamically, when you have a lot of variants of the algorithm, or when the algorithm has complex data structures that you want to encapsulate.
MVC uses other design patterns, such as Factory Method (107) to specify the default controller class for a view and Decorator (175) to add scrolling to a view. But the main relationships in MVC are given by the Observer, Composite, and Strategy design patterns.
...
MVC is a pattern. But it only covers a small aspect of a web application. Another common pattern that gets used with MVC is the Repository. These are more architectural patterns.... their scope has a bigger impact on the overall project.
the GOF patterns will introduce themselves in little ways all over the place. They can help build MVC infrastructure depending on design choices. eg, Strategy gets used a lot so you can plug in different ways of doing things like "authentication" etc.
You don't have to use the patterns as they are, they don't even have to be the exact same code structure. Its more the design principle / goal of the pattern that you employ in the design.
MVC is an architectural pattern. It perfectly fits with other design patterns like Command Pattern. But you do not apply patterns just because they exist and they are written in an authoritative book. You apply patterns when you have a programming/design problem and there is a way to solve that problem that was discovered by someone else and was written down. The way to solve a problem is a pattern. For example, you have an application that saves data to the database. Data to be saved is quite complex: some records must be inserted, some records updated and some deleted. The sequence of steps is important because the records to be inserted into one table depend on records to be inserted into another table. So, a database transaction must be used. One of possible ways to implement the transaction is to use Command Pattern. The way to do it is very well explained in Larman's "Applying UML and Patterns" book (chapter "Designing a Persistence Framework wth Patterns", section "Designing a Transaction with the Command Pattern" - scroll down to the page 556). PersistentObject is an abstract Model class there. All other Model classes extend it. In that example MVC is implemented in the UI, Application and Domain layers but Command is implemented in the Persistence layer. These patterns help to solve different problems and they are mutually supportive in that example.

Why is MVC so popular?

I was originally going to make this a longer question, but I feel like the shorter I make it, the better you'll understand what I mean.
The MVC architectural pattern has 3 dependencies. The View depends on the model. The Controller depends on the View and Model. The Model is independent.
The Layers architectural pattern defines N - 1 dependencies, where N is the number of Layers.
Given three Layers: Model, View, and Controller, there are only 2 dependencies, as opposed to 3 with traditional MVC. The structure looks like this:
View ---> Controller ---> Model
[View depends on Controller, Controller depends on Model]
It seems to me that this style accomplishes the same goals and produces looser coupling. Why isn't this style more common? Does it truly accomplish the same goals?
Edit: Not ASP.NET MVC, just the pattern.
With regard to griegs's post:
As far as mocking, Layers still allows you to use the Command Processor pattern to simulate button clicks, as well as any other range of events.
UI changes are still very easy, perhaps even easier. In MVC, the Controller and View tend to mesh together. Layers creates a strict separation. Both Layers are black boxes, free to vary independently in implementation.
The Controller has 0 dependencies on the View. The View can be written, and time can still be saved with loose coupling.
Because you decouple the interface from the controller making changes easier.
Also consider the scenario where you need to get started on a project but the artwork won't be ready for weeks or months. Do you wait or do you write all the code required for the pages and simply then wire up the view to the controller.
At least that's what we did and we saved months.
Also it made UI changes easier to cope with because there wasn't any code in our aspx pages that did anything.
Our tests were also better as we could mock up anything including button clicks etc.
And if you're talking about the asp.net-mvc framework, there is no code in the aspx files and no viewstate etc.
In proper MVC the controller doesn't depend on the view afaik. Or maybe I'm not understanding it correctly.
The model defines the data.
The view defines what the output looks like.
And the controller is a translator from a model-understood grammar to view-understood grammar.
So essentially the controller is independent. The view is independent. And the model is independent.
Yes? No?
I'll be bold, and try to explain why your method didn't catch on.
The MVC pattern basically requires the view and model layers to agree on an API.
Since one serves the other and there are no dependencies inside the code it leaves the controller to behave generically, all it needs to do is take a certain structure in the view layer and call the matching API on the model layer.
You'll note that agreeing on an API between the view and model isn't really such a big deal it has to happen anyway. And what you get is good separation between back-end front-end development.
In your proposed solution a lot of development is required on the controller side. The controller will be required to understand all the elements in the view and to map them to the specific calls required on the model layer.
Since the controller is a single access point connecting many views to many models this can quickly get out of hand and end up being an incomprehensible controller module.
Look at some Struts2 examples to see what I mean...
I think I'm understanding your point:
Yes you can make the View only depend on the Controller only by making the Controller transform (using PHP as an example) the Model objects to non-Model objects like simple arrays.
As we already know, performing this transformation can be more effort than it's worth if the decoupling isn't actually needed. If the View uses the Model objects then it has this dependency. However, this can be relieved a bit by having the View depend solely on the Controller for its required input, which can be Model objects.
The Symfony PHP framework promotes this style of skinny controller shuffling between Model and View. You can still directly call upon the Model layer to retrieve objects within the View layer but it's strongly urged against for the coupling issues you bring up. Within the View you can call include_component() which actually goes back up to the Controller if you need to query the Model.
I haven't gotten back to this in a long time, mostly because I was still thinking. I was unsatisfied with the answers I received, they didn't really answer my question.
A professor, recently, did steer me in the right direction. Essentially, he told me this: Layers which separate Model, View, and Controller is MVC. In the vanilla MVC architectural pattern, the dependency between the View to the Model is often not used, and you effectively end up with Layers. The idea is the same, the naming is just poor.
Choosing a presentation pattern for a new or enterprise web development on the Microsoft platform is a daunting task, in my opinion there are only three; View Model, Model-View-Presenter (MVP) or ASP.NET MVC (a Model2 derivative).
You can read the full article here ASP.NET MVC Patterns
I'd like to add some more things. First of all for my point of view is we use the model as container for the information we want to pass and show on the view. Usually the action method into the controller ends with return view("viewName",model).The view itself probabily will change its layour against the model :
on the view :
if(model.something==true) {
%>
somethign to show
<%
}
At this poinf the definition of model is hard to find.
I can say (especially on enterprise conext) the are two "model"
one is the domain model/entity model or how you want to call it that wraps the data coming from the lower layers (database,etc) and the view-model who contain the information we wants to show plus any other information we need to hide/show portion of interface
The controller orchestrate the the views and is indipendent from the view but a bit dipendent from the model:
into the controller
pulic actionResult Index(){
....
if(model.BoolProperty==true){
return ("firstView);
}
else
{
return ("secondView");
}
}
I hope it makes sense
In my opinion ,you'd better try it in your programme , you can use ruby on rails ,or codeigniter( for php ),these great framework may be helpful to your understanding the MVC.

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.

Resources