What are your favourite patterns for writing a controller?
This is rather a tough question as MVC is applied differently in different contexts. For example, for a desktop GUI, you might have listeners for event notifications of view changes but such behavior typically isn't used for Web forms (AJAX is changing this).
For the Web, you generally have:
Model: business logic
View: presentation logic
Controller: application logic
The controller should generally be minimalistic and if you find yourself pushing display information or business rules in it, there's probably a design flaw somewhere. Classic examples of such flaws in the controller are building HTML (view) or accessing the database directly (model).
I've written up a more thorough description of MVC on my O'Reilly blog. I have concrete examples there which can help explain things a bit more in depth.
Related
Can anyone explain difference between
MVC(Model-View-Controller)
and
MVVM(ModelView-ViewModel) architecture
?
Since MVC and MVVM are geared towards different application paradigms altogether, i.e., ASP.NET MVC for web and MVVM desktop, they need to behave in distinctly different ways, with the most noticeable distinction being the controller from MVC and the ViewModel from MVVM
The controller in MVC accepts HTTP requests, fetches data from the model, and routes that model to the view for output. In a desktop app, there is no routing or URLs; but desktop apps still feature navigation, which is part of the UI and therefore needs to be part of a good UI pattern. ViewModels are the piece that accomplishes this task, as the ViewModel in MVVM takes the responsibility of performing, or exposing the command that house all the UI logic in addition to fetching the data and data binding.
Views must behave differently as web and desktop applications use very different ways to render information for user interaction. Additionally, applications over http are considered stateless, whereas desktop applications have full connectivity over a LAN and contain and transport lots of data easily. Views in MVC only display data and perform basic client side UI duties usually with JavaScript (form submission, validation, effects, etc...). On the other hand, View in MVVM have a rich databinding and validation framework, when combined with the business logic and navigation exposed by the ViewModel, lead to a very rich User Experience
Models behave the same way in either pattern - they're full of data (and sometimes logic). You may want to use other patterns at the model level for better code organization, maintenance, and a finer separation of concerns. The repository pattern with Entity Framework is a popular pattern, and Julie Lerman has a great explanation within series of posts on it.
Within both MVC and MVVM exists the ViewModel. Despite the same name, there are marked differences within how ViewModels in either pattern work.
There are ViewModels in MVC, but they have different responsibilities than an MVVM ViewModel.
An MVC ViewModel is two or more models combined (smashed together), or a customized subset of a model or models that provides all the information necessary to its corresponding view. It's basically a hybrid model, and the best part - the views don't know the difference.
In MVVM, the ViewModel serves the same function as it does in MVC, but it also takes on the responsibility of a controller.
MVC Model and MVVM Model
MVVM is based on the MVC design patern.
MVVM is an implementation more specific for UI development platforms.
The separation between the development of the GUI and the development of the back end makes the development process more easy in these UI development platforms.
For more info on the difference, another topic already exists on this: Link to another stackoverflow topic
To my understanding, MVC is a way to implement the separation of presentation tier from business and data tier. Am I understanding this correctly? If so, MVC should separate the business logic completely from presentation, right?
So to me it seems like javascript (or jquery) is somehow violating the MVC design since it takes over some of the logic on the client side, isn't it? Is model = data tier, controller = business tier, view = presentation tier? I think I have misunderstood the whole concept.
You seem to have a decent understanding of MVC. The trouble is that you are looking at two different potential MVC structures as one and the same. On the server, you can have data models, controllers, and views. On the client side, you can ALSO have data models, controllers, and views. If you want to look at your client side JavaScript as MVC, then jQuery is simply a utility that the view controllers can use to manipulate the view (the DOM).
Simply put, the client side doesn't always have to be only the view. If you use a web application client-side framework like Backbone, for example, then you can have models, views, and controllers all on the client side, which communicate with another, SEPARATE MVC structure on your server.
What you describe does actually pose a challenge for a lot of implementations. Frameworks such as the ASP.NET MVC Framework have been making attempts to auto-render JavaScript to the UI based on business logic in the middle tier (validation rules for form fields, primarily). But they're a long way off from having a truly compelling JavaScript user experience which doesn't repeat logic.
Personally, I like to think of the JavaScript as purely a UI concern. The application internally handles all of the logic. The JavaScript, as part of the UI, may duplicate some of that logic... but only for strictly UI purposes. Remember that the application should regress gracefully into a still-working state if the user has JavaScript disabled. That is, it should still use server-side (middle-tier) code to get the job done. All the JavaScript did was add a richer user experience to the UI layer.
JavaScript isn't the only culprit for this, either. Suppose you have a lot of validation logic in your middle tier defining what's valid or invalid for your objects. When you persist those objects to a database (which is on the periphery of the application just like the UI is), doesn't that database also contain duplicate validation logic? Non-nullable fields and such.
Congratulations! Your understanding of MVC is completely wrong. It has nothing to do with n-tier architecture (which is what you seem to be confusing it with).
The core idea of MVC is separation of concerns. This is used by dividing the application it two major layers:
model layer: contains all of the domain business logic and rules.
presentation layer: deals it user interface
The presentation then is further split into controllers (for handling the user input) and views (for dealing with response).
When applied to web applications, you either have MVC (or MVC-like) structure only on server-side, or, for larger and more complicated applications, you have separate MVC triads for both frontend and backend.
Also, when working with applications, the user of MVC is not human being, but the browser.
In latter case the backend acts like one data source for frontend application. An the whole frontend part of MVC is written in javascript.
P.S. In case if you are able to read PHP code, you can find a quite simple explanation of model layer in this answer. And, yes. It is the "simple version" because MVC is a pattern for enforcing a structure in large application, not for making a guesbook.
You can go to http://www.asp.net/mvc site and refer tutorials / samples to learn about MVC using Microsoft technologies.
I've not really been able to differentiate between the patterns mentioned in the title.
A dynamic website has a user interface developed with basically HTML, CSS and maybe javascript (at least, that's what the user sees). The backend could be PHP or ASP (or whatever) which would be connected to a database.
I believe the database is the Model and the UI is the View. Is the backend a controller, presenter or viewmodel?
I'll appreciate an explanatory answer and, if necessary, links.
You cannot determinate which design pattern has been used for the application without access to the source code. And I get ad definite impressions, that this is what you are asking for.
Also you seem to be somewhat confused about what the are the parts of MVC and MVC-inspired design patterns:
Model is not the database. It is a layer (not a class or object) of application, that contains all of the domain business logic and interacts with at least one data source (which might or might not be a database).
The UI is maintained by presentation layer, which is mostly composed (mostly) from views and controller-like structures.
This microsoft msdn article WPF Apps With The Model-View-ViewModel Design Pattern describes MVVM as a microsoft customisation of Martin Fowler's Presentation Model pattern. His Passive View pattern is the MVP approach. His Supervising Controller pattern is the MVC approach. This older article takes about the evolution of such patterns. Not all languages and frameworks have good support for GUI patterns. MVVM for example was invented by Microsoft for desktop programming. Web pages typically have full page refresh rather than an event driven "desktop" programming model. It is arguable that trying to scale down the desktop patterns into a web page programming model distorts them beyond recognition.
A modern web framework that does have event driven programming model is ZK. This article Implementing event-driven GUI patterns using the ZK Java AJAX framework outlines writing the same simple screen three times using the three Martin Fowler patterns mentioned above. Everything is translated to html and javascript for the browser but the actual application screen code is running on a serverside event driven "desktop". What is the View, the Model, and the third part of the MVC/MVP/MVVM pattern is discussed in this presentation Design Patterns in ZK: Java MVVM as Model-View-Binder.
I've recently discovered that MVC is supposed to have two different flavors, model one and model two. I'm supposed to give a presentation on MVC1 and I was instructed that "it's not the web based version, that is refered to as MVC2". As the presentations are about design patterns in general, I doubt that this separation is related to Java (I found some info on Sun's site, but it seemed far off) or ASP.
I have a pretty good understanding of what MVC is and I've used several (web) frameworks that enforce it, but this terminology is new to me. How is the web-based version different from other MVC (I'm guessing GUI) implementations? Does it have something to do with the stateless nature of HTTP?
Thanks,
Alex
It appears that MVC1 (model1) did not have a strong break between the controller and the view where as in MVC2(model2), these concerns were separated.
See if this gives you any more insight: MVC1 and MVC2 discussion
More InformationJust a little more
I Think this is the main difference between MVC1 andMVC2:
The hallmark of the MVC2 approach is the separation of Controller code
from content. (Implementations of presentation frameworks such as
Struts, adhere to the MVC2 approach). But for MVC1 did not have a
strong break between the controller and the view.
Model 1 Architecture: - Here JSP page will be responsible for all tasks and will be the target of all requests. The tasks may include authentication, data access, data manipulation etc. The architecture is suitable for simple applications.
Disadvantages: – Since the entire business logic is embedded in JSP chunks of java code had to be added to the JSP page.
For a web designer, the work will be difficult as they mite face problems with business logic.
The code is not reusable.
Model 2 Architecture : – The servlet act as the controller of the application and will be target of every request. They analyze the request and collect data required to generate response to JavaBeans object that act as model of the application. The JSP page forms the view of the application.
Advantages: – Reusability
Ease of maintenance.
When you start a new web application, which pattern are you choosing between MVC and MVP and why?
(This answer is specific to web applications. For regular GUIs, see What are MVP and MVC and what is the difference?.)
Traditional MVC for GUI applications
This isn't really relevant to web applications, but here's how MVC traditionally worked in GUI applications:
The model contained the business objects.
The controller responded to UI interactions, and forwarded them to the model.
The view "subscribed" to the model, and updated itself whenever the model changed.
With this approach, you can have (1) multiple ways to update a given piece of data, and (2) multiple ways to view the same data. But you don't have to let every controller know about every view, or vice versa—everybody can just talk to the model.
MVC on the server
Rails, Django and other server-side frameworks all tend to use a particular version of MVC.
The model provides approximately 1 class per database table, and contains most of the business logic.
The view contains the actual HTML for the site, and as little code as possible. Basically, it's just templates.
The controller responds to HTTP requests, processes parameters, looks up model objects, and passes values to the view.
This seems to work very well for server-based web applications, and I've been very happy with it.
MVP on the client
However, if most of your code is written in JavaScript and runs in the web browser, you'll find lots of people using MVP these days. In this case, the roles are a bit different:
The model still contains all the basic entities of your business domain.
The view is a layer of fairly dumb widgets with little logic.
The presenter installs event handlers on the view widgets, it responds to events and it updates the model. In the other direction, the presenter listens for changes to the model, and when those changes occur, it updates the view widgets. So the presenter is a bidirectional pipeline between the model and the view, which never interact directly.
This model is popular because you can easily remove the view layer and write unit tests against the presenter and model. It's also much better suited to interactive applications where everything is updated constantly, as opposed to server applications where you deal with discrete requests and responses.
Here's some background reading:
Martin Fowler's encyclopedic summary of MVC, MVP and related approaches. There's a lot of good history here.
Martin Fowler's description of "Passive View", a variation of MVP.
Google's MVP + event bus
This is a new approach, described in this video from the Google AdWords team. It's designed to work well with caching, offline HTML 5 applications, and sophisticated client-side toolkits like GWT. It's based on the following observations:
Anything might need to happen asynchronously, so design everything to be asynchronous from the very beginning.
Testing browser-based views is much slower than testing models and presenters.
Your real model data lives on the server, but you may have a local cache or an offline HTML 5 database.
In this approach:
The view is very dumb, and you can replace it with mock objects when running unit tests.
The model objects are just simple containers for data, with no real logic. You may have multiple model objects representing the same entity.
The presenter listens to events from the view. Whenever it needs to update or read from the model, it sends an asynchronous message to the server (or to a local caching service). The server responds by sending events to the "event bus". These events contain copies of the model objects. The event bus passes these events back to the various presenters, which update the attached views.
So this architecture is inherently asynchronous, it's easy to test, and it doesn't require major changes if you want to write an HTML 5 offline application. I haven't used it yet, but it's next on my list of things to try. :-)
Both MVP and MVC make sense and allow to separate logic from display.
I would choose MVC because it's widely used in web development these days (Rails, .NET MVC which is used for SO) so my application will be more easily maintainable by someone else. It is also -to me- cleaner (less "power" given to the view), but this is subjective.
Another alternative is MTV, Model-Template-View which Django uses.