when we search Google for difference between MVC and MVP then thousand of article is available but i read few but they are not showing difference in terms of coding sample. so if anyone knows any url from where i can see a sample code for both MVC & MVP implementation then please tell me the url. i want basically small sample code by which shown the difference through coding flow in c#. i hope i am very much clear what i am looking for.....i need code same code one with mvc coding flow and another with MVP. i am not asking for theoretical explanation.
I also don't have sample code on my blog post "MVVM vs MVP vs MVC: The differences explained" but I do have a section for each architecture that discusses how to implement them using words. I will describe it here.
MVP requires a few implementation details
Each view must implement an interface for the view (eg IUserEditView for editing users). This interface contains functions for things that the presenter might need to do (eg, showUsers(IList users), displayMessage(String errorMsg)
A presenter is created for each view. It contains functions that the view will need to call (eg, saveNewUser(User user), selectedUserChanged(User user))
An instance of the presenter is created in the view's codebehind. When view events occur, appropriate messages are forwarded to the the instance of the presenter. eg, when the save button is clicked, all the user details are forwarded to the presenter in the form of a new user....myPresenter.saveNewUser(new User(txtUserName.text, txtPassword.text))
When the instance of the presenter is created in (3), the view is passed as an argument to the constructor. This way, the presenter can reference the IUserEditView from (1)
That is the meat of MVP. You will probably need to implement the mediator pattern and have all the presenters inherit from base presenter. This way, presenters can send messages to each other without having to reference each other explicitly which is important (eg, if a new user is added, maybe you need to update a related view like users online).
MVC is a bit more tricky.
The controllers have a method of selecting which view is displayed. This could be referencing just a dictionary of instances of all the views but a better way is to have some class outside the controller manage the details and then the controller can just select the view with something like ShowView("UsersView", listOfUsers). Note the separate class can be a base class, or a factory, helper
A method of forwarding actions from the views to appropriate controllers. With the web, you just can determine the controller & method from the request url (eg, http://www.mysite.com/mycontroller/method, www.mysite.com/Users/AddNew/). For other systems, you will have to implement a class to manage the messages, or just directly forward them to an instance of the controller in the view. I've only used MVC with the web so I'm not so sure about the last point.
Because of (2), the view is now able to trigger actions in the controller. When it does so, the controller modifies the model (the implementation of this will depend on the details of your model).
Updates to the model get sent to the view (usually via an observer pattern). Check out INotifyPropertyChanged if using .net
Word of caution: Although I have described how to implement both methods, they should not really be considered interchangeable. There are cases when you want MVC, MVP, and MVVM. I think if you don't have technology limitations around using MVVM, then it is your best choice. I am biased but I think maybe people are moving away from MVC and towards MVVM (or MVP) except for very specific cases like ASP.NET MVC. My article describes this in more detail if you need clarification.
Short summary for when to use each in terms of C#
WinForms -> MVP
WPF -> MVVM
ASP -> MVC (if you can't use ASP.NET
MVC, then MVP will work too)
Related
Sorry for the vague title. I am pretty ashamed to ask this but I really need my awareness right now. I cannot identify whether I am following an MVC pattern or MVVM pattern.
In my previous internship, we had C# code (.NET) which had a controller and connected directly to the database (there wasn't a service layer). The controller would fetch information, format into JSON and give it to Angular's controller, which would display it on the view.
In my current internship, we don't use Angular. We use .cshtml files. The service layer provides its information to the controller, which formats the MODEL and gives it to the .cshtml view and which displays the content.
My questions:
Which one is MVC and which one is MVVM? Please drop down to my level and explain. Most of what I've read on the web seems to confuse me more with what I observe at work.
Everyone at work calls both of them MVC and, I am really confused now. If both are MVC, what's the difference between the two?
Angular is definitely more Model-View-ViewModel-ish. Whereas what you're doing now definitely sounds like MVC.
MVVM is a special pattern where the UI state is encapsulated in a ViewModel, so that the rendering of the final UI is fairly dumb and just data-binding. The state logic to say, show this button, or hide this area is all encapsulated in the ViewModel. One benefit, is that this allows for unit tests to be built to test the ViewModel and thereby implicitly testing all of the UI behaviors. (see: Wikipedia article on MVVM and Martin Fowler's Introduction to Presentation Model which MVVM is a variation of.)
In MVC, the view itself has the latitude to control it's behaviors, what you want to show/hide, etc based off of the data provided, the model. This means that in MVC, you can't test the UI behaviors (e.g. if something is correctly showing or hiding based on data changes) without testing the UI itself.
So in summary, MVVM, the ViewModel controls the UI behavior and the UI itself is dumb and just uses data-binding and does what it's told to do based on the logic in the ViewModel.
In MVC, the UI is 'intelligent' and re-shapes and renders itself however it feels it needs to based on the data it receives from the model.
You can basically look at how the UI is rendered and if you see the UI rendering logic making a lot of its own decisions about how to render itself based on the decision, then you pretty much know you're using MVC. If you just see a lot of data-binding, where almost every behavior is driven by a separate class that encapsulates all of the logic for showing and hiding pieces of the UI and this data is passed to the UI via data-binding, then it's probably MVVM.
I hope that helps.
In both cases, you are using MVC (or at least an MVC-ish pattern). When using the .cshtml files, you are using server-side MVC. When using Angular, you are using client-side MVC (which is probably more like MVVM). The biggest difference is where the model is rendered into HTML elements; on the client, or on the server.
In my opinion, this is a better way to view the differences in what you have done.
We're porting an existing Silverlight application into AngularJS/Typescript.
The application has a classical MVVM structure with data models, view-models and views. The models are somewhat tightly interconnected: for example, there are IObservable<> event streams which notify container models of changes within child models.
Here's what confuses me: in MVVM, everything that binds to view is a view-model. One view-model may have a list of other view-models that it contains. In all AngularJS tutorials for people with WPF/Silverlight background, however, only the $scope is called a view-model. What about the nested objects? Are they just domain data models, and you bind to them directly without any intermediate view-model layer?
Then, there's another question: if my data object changed somehow (for example, some service updates it when receiving data from the network, or it simply does some work based on timer), how do I notify the view that it should be updated?
First, I would like to say that you shouldn't try to match one technology to another technology. Doing an app in C# is not doing an app in Javascript (or any flavor of it) so trying to put a name on how the silverlight things are called on Angular/javascript is not a good idea.
What I would suggest is you (and your team) learn how Angular applications are made, what components are used for what purpose and then port the IDEA to angular. Coding an Angular app like a silverlight app is not a good idea.
Anyway, for the sake of the answer, I'll answer some of your questions since I am familiar with WPF / Silverlight.
In angular there is no real need to implement any observation pattern (there is pubsub).
Normally you have services which do a couple of things, like a repository pattern to access your backend or hold your data to use in different pages. Since services are singleton, if you modify it from pageA, pageB will know, so there is no need to tell, that is implicit.
$scope works as a glue between your controller and your view. Since $scope holds POJOs (plain old javascript objects you can put in there anything you need. You can have there nested objects or functions. Then you can use those properties on the $scope in the view without any problem.
If a Service query a backend, it updates the service's data and every controller using that service will automagically get the updated content. The trick here is to know is that you don't have to kill the reference and just update the value.
So, take a little time to learn Angular without having Silverlight in mind, learn what every piece does and start working. That is my advice.
i've created a forum system in MVP pattern but i'm not sure if i implemented it in a right way. so here is what i ended up with:
i've created a database which has three tables: forums, threads, posts
added a new typed dataset to the project and then dragged all the tables into it
created three new calsses: ForumsModel, ThreadsModel, PostsModel
added three interfaces: IForumView, IThreadView, IPostView
three more classes: ForumsPresenter, ThreadsPresenter, PostsPresenter
inside the model classes i just call the typed dataset methods and in presenter i've called the model methods. the views are .aspx pages. that's all there is for the forums system but here is the tricky part:
since MVP pattern is an UI pattern i have to do the validations of data in Application itself. so with my design the MVP is the application!
what did i do wrong??
edit 1: first of all about why i chose typed dataset with stored procedures over other options: it's the lightest data provider that doesn't compromise whatever architecture you have. other options are direct sql which is not a good option for newly created application, LINQ to sql classes which are too heavy to be instantiated with each request, Entity Framework which is great but is too much for such a simple task! at least if i was creating a blog engine it would have been my first choice.
as for the why i didn't choose MVC, it's because i think MVP is the better pattern since it'll give me complete seperation of different parts of my application. at the end it's a matter of tase but you should be able to implement any pattern, right?
i've seen different flavors of MVP but the one i'm trying to implement is this:
model<------------->presenter<-------------->view
the databind option is for the presentation model pattern which is introduced by martin fawler as far as i remember but the one i'm trying to create is a microsoft version which basically is an extended version of the PM pattern.
two days ago i asked a question about data validation and someone suggested that i should do it in "Application itself" so when i asked where is this "Application" he said that the MVP is an UI pattern and it shouldn't be your "Application" and you should implement the MVP in your user interface layer. so that's the reason i asked this question at the first place!
With MVP the code behind becomes the View implementation based on a View interface.
The View interface contains the page events the Presenter will need to bind to in order to change the state of the View, as well as properties and methods it might need. For instance it could hook onLoad event and call into the View to change it's state. In doing this it's agnostic to the View implementation and knows nothing about controls. This means you can write unit tests without an ASPX instance.
To create a MVP engine that automates wire up, you would make use of a base page, generics and IoC. The IoC allows you to set dependency overrides for things like WebContextBase which is visible to only that request pipeline, and which can be passed to your Presenter constructor.
IoC also allows you to inject other dependencies Into your Presenter to help keep it light weight. This way you can move business and data access to other layers.
MVP is really useful where you have to use WebForms, such as with most CMS systems. If you aren't constrained, then use MVC.Net for new web development.
Update: As promised here's a fairly decent example. The bit it's missing is the dependency overrides which can be done like this:
var dependencies = new DependencyOverrides
{
{typeof (HttpRequestBase),new HttpRequestWrapper(Request)},
{typeof (HttpResponseBase),new HttpResponseWrapper(Response)},
{typeof (IPrincipal),Context.User},
{typeof (IIdentity),Context.User.Identity},
{typeof (IUserProfile),Context.User.Profile},
{typeof (HttpSessionStateBase),new HttpSessionStateWrapper(Session)}
};
presenter = container.Resolve<TPresenter>(dependencies);
You made an architecture mistake by choosing webforms over the ASP.NET MVC framework. Also typed datasets are so 2003, you should use Entity Framework. Get with the times!
Have you looked at ASP.NET MVC? It's the Model-View-Controller pattern, and will handle all the routing and plumbing for you. You'll get easy model validation with DataAnnotations, and there's plenty of Resources and Tutorials
Or is there a specific reason why you need to use the MVP pattern with classic ASP.NET?
Since your question was not about the merits of MVC vs MVP or Typed Dataset vs Entity Framework, I am assuming you have a compelling reason to do things the way you are doing them.
With that out of the way, you don't seem to be doing anything wrong. With MVP, validation is supposed to take place in the Presenter implementations, as they have access to your view instances during postbacks. Of course you could also use client side validation with javascript.
I am a asp.net developer and don't know much about patterns and architecture. I will very thankful if you can please guide me here.
In my web applications I use 4 layers.
Web site project (having web forms + code behind cs files, user controls + code behind cs files, master pages + code behind cs files)
CustomTypesLayer a class library (having custom types, enumerations, DTOs, constructors, get, set and validations)
BusinessLogicLayer a class library (having all business logic, rules and all calls to DAL functions)
DataAccessLayer a class library( having just classes communicating to database.)
-My user interface just calls BusinessLogicLayer. BusinessLogicLayer do proecessign in it self and for data it calls DataAccessLayer functions.
-Web forms do not calls directly DAL.
-CustomTypesLayer is shared by all layers.
Please guide me is this approach a pattern ? I though it may be MVC or MVP but pages have there code behind files as well which are confusing me.
If it is no pattern is it near to some pattern ?
That's not four layers, that's three layers, so it's a regular three tier architecture.
The CustomTypesLayer is not a layer at all. If it was, the user interface would only use the custom types layer and never talk to the business layer directly, and the data access layer would never use the custom types layer.
The three tier architecture is a Multitier architecture
As far as patterns go, I recommend getting to grips with these:
My biggets favourite by a mile is the Dependency Inversion Principle (DIP), also commonly known as (or at least very similar to) Inversion of control (IoC) ans Dependencey Injection; they are quite popular so you should have no problem finding out more info - getting examples. It's really good for abstracting out data access implementations behind interfaces.
Lazy Load is also useful. Interestingly, sometimes you actually might want to do the opposite - get all the data you need in one big bang.
Factory pattern is a very well known one - for good reason.
Facade pattern has also helped me keep out of trouble.
Wikipedia has a pretty good list of Software design patterns, assuming you haven't seen it yet.
A final thing to keep in mind is that there are three basic types of patterns (plus a fourth category for multi-threaded / concurrency); it can help just to know about these categories and to bear them in mind when you're doing something of that nature, they are:
Creational
Structural
Behavioral
Take a look at the Entity Framework or LinqToSQL. They can both generate your data access layer automatically from your database. This will save you a lot of (boring) work and allow you to concentrate on the interesting layers.
Code-behind does not really have anything to do with architecture - it is more of a coding style. It is a way of separating logic from presentation. Any architecture you mention can be used with or without code-behind.
You seem to be describing a standard three-tier architecture. MVC is a pattern than describes how your layers and the user interact. The user requests a page (represented by a View), which requests its data from the Controller. The Controller communicates with your business layer (Model) to extract the correct data and passes it to your View for display. If the View is interactive, for instance it allows the user to update something, then this user action action is passed back to your Controller, which would call the relevant method against the business layer to save the update to the database.
Hope this helps.
I am primary a web developer but I do have a very good understanding of C++ and C#. However, recently I have writing a GUI application and I have started to get lost in how to handle the relationship between my controller and view logic. In PHP it was very easy - and I could write my own MVC pattern with my eyes closed - mainly because of how PHP is stateless and you regenerate the entire form per request. But in application programming languages I get lost very quickly.
My question is: how would I separate my controller from view? Should the view attach to events from the controller - or should the view implement an interface that the controller interacts with?
If I was you I would expose events from an interface of your view. This would allow you to make the controller central to the entire interaction.
The controller would load first and instantiate the view, I would use dependency injection so that you don't create a dependency on the view itself but only on the interface.
The controller would access the model and load data into the view.
The controller would bind to events defined on the view interface.
The controller would then handle saving of data back to the model via an event.
If you wanted to you could also use an event broker which would void the need to declare an interface per view. This way you could bind to events through attributes.
This would leave you with the Controller being dependent on the model and the view interface, the view being dependent on the data only and the model having no dependencies.
Some examples of the above design thinking can be found in CAB and the Smart Client Software Factory Link To Smart Client. They use the MVP pattern but it could equally easily be applied to the MVC pattern.
Most every GUI framework (from MFC to SWT to whatever) is already MVC based. In fact, the MVC pattern was first created by Smalltalk-80 and later first really used for GUI development.
Double check and look at the standards and suggested practices for your GUI toolkit of choice. Sometimes MVC won't be a good pattern to work with when solving a certain problem or working with a particular toolkit.
Remember: MVC is a great pattern but isn't a one size fits all solution, don't try and force a problem into MVC when event-based or functional style programming will make your life easier.
Imagine this GUI:
The Zergling unit is presented to the user as an alien icon. You can see that it is in its idle animation. Call this the View.
The player moves the unit by clicking on it and a target location. You can subtitute the player for an AI if you want. Call this the Controller.
The HP and attack range of the unit is calculated every game frame when the unit is in combat. You can change this data to make the Zergling into a range unit. Call this the Model.
Keep this analogy in mind and extend it for your MVC designs.
The imortant thing for you to remember, is that in your MVC setup the Controller must know which View to call, but the View must know nothing of the Controller.
So your View must provide a generalized way for Controllers to interact with it, so that you can have several different Controllers call the same View (a standardized graphical output of some data provided as parameter, for example).
This gives you flexibility:
If your customer wants PDF output of
something you only provide HTML
output for, you can get away with
writing a new PDF View to be called
from the Controller with the same
parameters as the HTML View.
If your customer wants similar HTML output of a different data source (say), you can get away with coding a new Controller that provides a different data set to the same old HTML View, which gives the same HTML report just with other data.
If you keep your View detached from specific Controllers, and put the knowledge about which View to call from your Controller, you're well on your way.
Your controller should definately bind to events defined on an interface the view implements.
How you go about doing this can be the tricky part. Dependency injection? A view factory? Have the view instantiate the controller it wants? It really depends on how complex the application is going to be.
For something really quick and simple I would start with having each view construct it's controller and then look at other options if it needed to get bigger. Personally I think a full dependency injection framework is overkill for half a dozen forms :]