Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Model View Presenter - use data binding? 2

Status
Not open for further replies.

JoeAtWork

Programmer
Jul 31, 2005
2,285
0
0
CA
I'm currently researching the Model View Presenter design. I am working with .NET C#.

In some of the articles I have read, they give examples of the Presenter setting properties of the View, then in turn the View updates it's controls. For example in the Presenter you might have the following method to update the customer information shown on the view:

1 private void UpdateView(Customer customer)
2 {
3 _view.CompanyName = customer.CompanyName;
4 _view.Address = customer.Address;
5 }

In the view, I would create corresponding setters for CompanyName and Address.

What I am wondering, could I use databinding instead of these setters in the View? I.e. I create CompanyName and Address properties in Presenter (which passes on updates directly to Model), and the View binds it's controls to these properties.

To take this even further, I am wondering if I can bind directly to the properties of the business object (the Model)? In at least some of the articles I've read, it is permissable for the Model to send notifications directly to the View. The Model would not know which views are subscribing to these notifications, so the separation of concerns is still enforced.

It would seem that direct data binding bypasses the role of Presenter, however I would still use Presenter for all other coordination of the UI (for example, deciding when the Save button can be enabled). I am just thinking that when there is a direct relation between controls in the View and properties of the Model, why not use data binding as the coordinating mechanism, rather than a bunch of setters that need to be implemented in the View?


 
YEs the model sends out notifications to the view via events in C#, this still is low coupled because th model doesn't know which view is acting on the changes. This is an implementation of the observer-pattern. I would advise against databinding because it tightly couples your view to your model. The view knows about the model which is not a good thing. What if the model changes? Which one of the two methods will have you need to do the least changes? BTW your view can depend on more than one presenter and perhaps even more than one model. And yes the view can get overly complex with all the properties. And don't forget that you would always create an interface of your view or multiple interfaces and your presenter only knows about your interface (an IoC like structuremap, castle windsor,... will help you inject the implementation in the presenter). These will cut down on the coding somewhat since the ide will generate parts of them.

I typically only use databinding for datagridviews. All the rest can be done without binding.

I hope that helps.

My personal view on this is, that if you can replace your winforms view with a webforms view without having to recode the presenter, you have a good presenter since it is view-independent. But I don't think that view is shared by everyone. And like most things in programming you will find hundreds of different methods to implement it.

I guess you were also looking at passive view where the view has properties to set and get it's controls. It is kinda nice but becomes very troublesome when having very rich forms(pages) (forms with lots of menuitems and user interaction.) Then supervising controller is better. I would only use passive view for smaller/simpler forms.

I hope you understand what I'm saying.

Christiaan Baes
Belgium

My Blog
 
chrissie, is there a good example online about supervising controlers? I tend to favor passive view (my projects are simple) Is supervision controller another term for MVC? (mono rail and MS MVC)

Jason Meckley
Programmer
Specialty Bakers, Inc.
 
Supervinsing controller is one of the two patterns that came out of MVP and in fact MVP no longer exists.

You can read more about supervising controller here
Martin fowler is the one that came up wit the MVP pattern and then split it up in passive view and supervising controller.

you can also look at Jeremy D millers how to write a cab series

see here for a start

Christiaan Baes
Belgium

My Blog
 
chrissie1 said:
I would advise against databinding because it tightly couples your view to your model. The view knows about the model which is not a good thing. What if the model changes? Which one of the two methods will have you need to do the least changes?

That was my thought at first, but on further reflection it didn't make as much sense.

My thought was that if I bind directly to the model, then I must make a reference to the specific assembly that contains the Model objects, and that would be bad because it would be close coupling.

However, something has to have a reference to the specific Model you are using, and it would seem that that would be the Application that contains the Views. Now, as long as the View isn't binding itself to the Model, but rather something outside of the View (like the Main subroutine of the application) is hooking everything together, then it's not really close coupling. If I needed to switch from ModelA to ModelB, it would only be one line of code to change in the application:

Code:
  IModel myData;
  [COLOR=green]// myData = new ModelA();[/color]
  myData = new ModelB();

  [COLOR=green]// Set up binding of controls to properties of myData...[/color]

ModelB has all the properties that ModelA had, no other code would need to be modified.

What I am trying to figure out is if it is truly necessary to have Presenter to be a middle-man for properties that are one-to-one mappings between View and Model. For example, why do this:

View.CompanyName -> Presenter.CompanyName -> Model.CompanyName

instead of directly:

View.CompanyName -> Model.CompanyName

Now, I know the answer is that Presenter is supposed to be a layer between the UI and the business object, so that validation logic and other behaviour will be consistent, no matter which View. However, I am using CSLA business objects, which already track their own broken business rules. For most of these one-to-one mappings, I can't see any extra processing that Presenter could do, so why not pass the value directly to the Model?

Even if the value is invalid (let's say an empty string for the CompanyName property), I could still pass it directly to the business object, which would cause it to be in an invalid state. Presenter would be monitoring events on the business object and would know immediately when the business object becomes invalid, and would pass on the appropriate notification to the View (which as a response might disable all save functions, in this example).

Presenter is still controlling all the behaviour of the UI - which is the point of MVP as I understand it. It's just as loosely coupled, because View is not setting up it's own binding - it could just as easily be bound to ModelA, ModelB, or ModelC, assuming they all implement the same IModel interface.

So would binding directly to the Model in such a case break the benefits of using MVP?


 
phew, CSLA is not my cup of tea since I think the model should never have CRUD behaviour in it. Why should my invoice object have a save method? If you use CSLA you should follow lothka more closely and read up on that, perhaps even go to his forum since there are more people that can help you. But I still think using databiding like you want, is not the way to go and leaving out the presenter or controller is not a good idea.

And who will handle the printinfg of reports? the navigation to other pages/forms. I think CSLA makes the model object much to heavy. But that is my personal opinion and I think you need to find something with which you feel comfortable. The reason for the presenter is usualy because it eassier to test.

Christiaan Baes
Belgium

My Blog
 
chrissie1 said:
Why should my invoice object have a save method?
How else would I save changes to the database? I wouldn't think that interaction with the data layer is not appropriate in either the Presenter or the View.

Technically a CSLA business object in the role of a Model doesn't have CRUD behaviour. The code for saving to the database may physically exist in the same class, but logically it is only called on the server (unless the database is local, in which case the client is also the server).

I'm doing this because I was told to use CSLA and MVP for this project. So I'm following orders as best I can. The research is quite interesting and I am coming up with some ideas (maybe half-baked). I'm quite curious how this baby will turn out.

 
I always create a service in between my mvp and dal and call the dal from the P giving them eiter a DTO or a BO but then my all my BO's have interfaces and I only pass interface around. Nearly everything has an interface in my design which makes IoC/DI much eassier ;-).

the service(s) can take their data from anywhere. As long as you use a factory to get to the services.

and yeah you could consider the save method as a buitlin service. But still I think it doesn't go well with Soc (Seperation of concerns.

But like I said (or not) after doing much reading I have come to the conclussion that there are several ways of going about this and a lot of them are good. As long as most of your methods are short and to the point you are on a good path. And the only way to find out if your wrong is by doing it. Of course that is bad advise if you are pressed for time. But then maintainability is probably not your main concern ;-).



Christiaan Baes
Belgium

My Blog
 
Actually maintainability is the whole point of this exercise. My project manager on a quest to create the "perfect" architecture for our project. We are making an application for a specific customer, but our goal is to make it resellable to others in the industry.

Hence, we are trying to design an architecture that allows for flexible customization.

My PM spends most of his time researching design patterns, architectures, etc. He has concluded that MVP is the best solution for our goals. We are using CSLA because quite frankly that is the only business object framework that we are familiar with.

I guess it is time for me to open up Visual Studio and try out some of these ideas.

 
Apart from me, nothing is perfet ;-).

I don't see a need for an Object bussines framework myself.

Christiaan Baes
Belgium

My Blog
 
chrissie1 said:
I don't see a need for an Object bussines framework myself.
Gasp! Heretic!
So, you don't have a Business tier between Presentation tier and Data Access tier?

Where do you check and enforce the business rules?

What architecture do you recommend for an application that needs to be maintained and enhanced over a minimum five year period?


 
Yes I have a bussiness layer, but not a framework as such. My bussines objects are just classes with properties and methods they don't inherit from a big superduper motherclass that does all.

5 years is a long time in computer history ;-)

I would go for this.

View = does only view things and for all the rest goes to the presenter
Presenter = the glue between Model and View and handles the events from the model and then passes it on to the view (not strict MVC since MVC has the view handling the events of the model).
Model = the bussines layer
Servicelayer = a layer between MVP and the dal/webservices/remoting/xmlfiles
DAL = persist the data any way you like

of course I would use an IoC/DI container, logging and ORM in some cases DTO's and TDD (before or after) with a mocking framework. Some source control comes in handy. And testing lots of unittests. Did I mention unittests?

Did I forget something? Of course, I'm not an architect per say. ANd don't forget the .Net is not quit ready yet for OO programming especially the view side. It has improved in 2008 but sometimes you need to hack you way thru to get the result you want. And if performance is an issue some of the maintainability will be thrown out of the window. And don't forget to look up code smells (a select case in your code is ussually a bad sign (strategy pattern).

And don't forget that a project ussually ends up being refactored somewhere in the middle when you see the light. Ussually because somebody forgot to mention some really important requirement, like they want all the buttons to be blue.

And another one, the users couldn't care less wether or not your application is maintainable and has pretty code.

I'm sorry if I can't explain better, I'm not good with english words.

Christiaan Baes
Belgium

My Blog
 
How else would I save changes to the database?

My dumb-data-layer is built-up as follows

Backend
\Employees -> Employee
\Projects -> Project

Etc. For each type of object in the model (that can be seen as a "record wrapper" if you are a database guy), there is a collection. These collections are responsible for handing you the specific objects. In human terms, you would compare such a collection with, say, a shop owner. The shop owner's responsibility is to ensure that there is a good number in stock. But all transport, manufacturing, etc is delegated to others. So all thing "come from the shop" and how it gets there in the first place is not interesting.

You can see the shop as a "table wrapper", but the shop does a real lot more. The main reason that my shop exists is that it defines the data strategy. This can be lazy, greedy, side-caching, you name it. Now these strategies can never be enforced by telling each book to store itself. Or, even more absurd, by creating a book and then asking it to create itself.

But you asked how to store changes to a database, so we'll take the shop's back door. The shop has a backdoor, through which the goods arrive. This is fundamentally different from CRUD methods.

CRUD methods make the shop owner break into the factory or distributor's warehouse, and take everything himself. And bring everything himself too. Why would a shop owner do that? Such things are best left to a transporter!

So my code does it radically different: I have DataLines that push data (usually based on an ID or a code) to the collection. Anyone with access to that dataline can now bring goods to the collections "live" memory. And any number of DataLines can. For instance, A DababaseLine, a WebserviceLine, a CentralCasheLine, you name it. The collections can also store things through data lines. One of the nice things is that these datalines can be "splitters" or other composite types. You just "plug" the collection to any data storage you want. For getting data, you plug the collection to the data lines, and not the other way around.

One final note about CRUD on single objects: This is absurd. It is absolutely impossible to grab someone by the arm and tell him to cease existing, because I am holding him to be able to tell him. Also, I cannot first create a stateless object and then tell it to get an identity and to always have needed one. This is really absurd. It is the collection that can remove all links to an object and makes sure it disappears from the storage as well. The member objects do not even know that they came from a storage, for the simple reason that they did not even exist when their data arrived. They can not even exist without their data, because they are persistent objects. They have identities by their very nature. If you allow these objects to exist without an identity in whatever point of their existence, you open a really nasty big can of worms. Persistence can never, ever, be the responsibility of a member object ("record wrapper").

Sorry I did not name any know design pattern here.


+++ Despite being wrong in every important aspect, that is a very good analogy +++
Hex (in Darwin's Watch)
 
DonQuichote's collection objects are my services. But he calls a horse a horseand, me I call it a paard.

But he agrees on me about CSLA, allthough he is scared to say it ;-).

Christiaan Baes
Belgium

My Blog
 
I think I am missing a book or two from my reference library to know how to implement the design that Chrissie and DonQuichote are suggesting.

If I built a service layer, which I guess is basically a set of factory methods to deliver my business objects, I can see myself making something like:

Code:
public Customer FetchCustomer(int CustomerID)
{
  // Retrieve data from data access layer
  // (the DAL will call a stored procedure on the database)
  CustDTO dto = DAL.GetCustomer(CustomerID);

  // Set up a Customer business object
  Customer customer = new Customer(dto);

  // Return populated customer to caller
  return customer;
}

Essentially it is the same thing I would be doing with a CSLA business object.
1. Call a stored procedure to retrieve data about the customer
2. Inject that data into the business object
3. Return the business object

I suppose what I am missing is an alternate strategy to the one I'm using, which is essentially to call a stored procedure each time I need to populate the business object.

I guess an example of one of your "strategies" would be to cache frequently used items. Like loading the 10% most frequently bought products and keeping them in a special collection, so every time a product is asked for I first check if I already have it in the cache. Would that be an example of a "strategy" which can't be implemented with CSLA?

 
Hi Everyone,
I am a programmer working with Joe. There are some great points raised in this post. I agree that Csla is a big fat pig with lip stick for lack of a better description. Unfortunately this is just something we have used for a long time. Perhaps this is the project to switch.

Would one of you be willing to post an entire .net solution that is representative of how you typically implement business objects?

Also is the active record pattern the implementation as per martin fowler?

One small challenge. I don't think fowler created the MVP pattern rather it came out of a small talk evolution as a result of not being satisfied with MVC.

Thank you,

Rob
 
I'm still not sayig that CSLA is bad perse, mr. lothka happens to be a very smart man. But it just doesn't agree with me. And I'm not saying you have to change. Do you think your applications with CSLA are unmaintainble?

And I' am writing a solution but you will have to wait for LTD (ask Joe) to go live to see it. And that could take a while ;-).

A bussines object looks like a domain-model object in your OO-design. this thing
yes active record like CSLA uses is what Martin fowler describes.

Small challenge, I don't think anybody creates patterns, someone just describes them. And I think MF just did that.
You first write good code and then you look to see if you have a pattern that can be repeated. And some people just are better at describing things.




Christiaan Baes
Belgium

My Blog
 
I agree Rocky Lothka is a very smart man. His framework is great but it doesn't sit with me either as I am trying to create a very custom MVP implementation which I am calling the Firegarden Framework. It's essentially small talk MVP pattern implemented in WPF.

In order to make this happen it feels like we need more control over the model. The model in MVP is supposed to be an object which touches no one. It raises events and manages state. So perhaps really we are just talking about issuing change notifications for properties and collections. In that case investigation into change notification interfaces in WPF and routed events would lead us to the an answer.

If our model implementation consistently handled these issues the framework could utilize csla. Still there are outstanding issues with binding validation in Csla. and Data transfer objects maybe a better alternative for persisting state using WCF into a service layer.

Thank you,

Rob
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top