Build your own CAB (转与 Jeremy D. Miller )

来源:百度文库 编辑:神马文学网 时间:2024/04/27 04:45:43
Build your own CAB Part #1 - The Preamble
Yesterday I made a somewhat unsubstantiated claim that you simply don‘t need theComposite Application Block (CAB) to build nontrivial WinForms user interfaces in a maintainable fashion.  I claimed that mere mortal developers can master the underlying design patterns in the CAB and pick up a better Inversion of Control/Dependency Injection tool to organically grow an application structure that meets the specific needs of that application.  I even think that mere mortals can do this as or more efficiently as they can by utilizing the very generalized CAB.  To try to substantiate that claim, and because there seemed to be enough interest to warrant this series, I‘m going to convert my WinForms patterns talk fromDevTeach into a series of blog posts to demonstrate some design strategies for creating maintainable WinForms code.  Even if you‘re going to stick to the CAB (and that is a valid choice), I can hopefully add to your ability to use the CAB by exploring the very same patterns you‘ll find lurking underneath the covers in the CAB.  If you like the way the CAB does something better than the ways I present, please write in and say so.
One of my favorite authors isAlexandre Dumas, author of the Three Musketeers books and the Count of Monte Cristo.  The Three Musketeers was the soap opera of its day, written in installments as a serial in whatever passed for magazines in those days.  Likewise, I‘m going to try to dribble these posts out in little installments.  Basically the size of post I can write in a single sitting on the train ride from and to work.
Note on terminology -- I‘m a card carrying Fowlbot, so I‘m using the terms set forth inMartin‘s forthcoming book on enterprise design patterns.
It‘s just the User Interface right?
"Just" the user interface?  I haven‘t seen this so much lately, but earlier in my career there was a definite attitude that User Interface (UI) programming was simple, grunt work -- unworthy of the attention of the serious developer.  In my mind I always think of the line "Just pick it up" from Caddyshack, or Kramer extolling Jerry to just "write it off."  That‘s a dangerous attitude because user interface code can easily be much more complex than the server side code in many systems.  It‘s worth spending some mental cycles on the design and structure of the UI code.  Here‘s why:
Creating user interface code is time intensive.  Not just in terms of the initial coding, but in my experience UI code generates the most defects and hence takes the most time to fix bugs.  We can cut down the defects by extending unit testing as far into the user interface code as possible.  TDD opponents often use the UI as an example of code that just can‘t be tested.  They‘re wrong, but UI testability doesn‘t come for free.  It takes some care to craft a structure that makes UI code easier to test. User interface code interfaces with an extremely unpredictable external dependency -- those wacky users!  It takes a great deal of care to protect the system from garbage input and user error. The User interface changes frequently.  Again, my experience is that it‘s much easier for a user and analysts to get the backend logic requirements upfront than it is to specify the user interface.  Making the UI code easier to change just makes sense, but that again takes some design cycles. UI code is largely event driven, and event driven code can be nasty to debug.  Again, testability and a cleaner separation of concerns makes that debugging either go away or at least become easier.
A Note about Design Patterns
I know many people blow off design patterns as ivory tower twaddle and silly jargon, but I think they‘re very important in regards to designing user interface code.  Design patterns give us a common vocabulary that we can use in design discussions.  A study of patterns opens up the accumulated wisdom of developers who have come before us.  Finally, the design patterns we‘re going to examine in this series give us a framework of ideas on the best way to divide responsibilities in our user interface code.  That‘s a good thing because...
User Interface code contains a lot of different responsibilities
It was almost comical, but sitting in the Agile track at DevTeach almost every speaker, including me, had at least one slide dedicated to theSingle Responsibility Principle (SRP).  Just to recap, the SRP states that any one class "should have only one reason to change."  Basically, you should strive for each class to contain a single coherent responsibility or concern.  Like I said before, UI code can easily become complex.  Just to prove that point, let‘s list some of the responsibilities that could easily be contained in a single screen:
The actual presentation to the user Capturing to user input events Input validation and business rules Authorization rules Customization Screen flow and synchronization Interaction with the rest of the application
Lots of important things.  Lots of things that would really be easier to code if I could just work on one thing at a time.  Things I‘d really like to be able to test in isolation from one another.  Back to the Single Responsibility Principle, we can better enable change and improve maintainability in our UI code by assigning each of these responsibilities to distinct, loosely areas of the code.  What we need is some sort of divide and conquer strategy for our WinForms code.
Of course, a large problem in WinForms development today is that the most common pattern of assigning responsibilities is...
The Autonomous View
You might not be running around saying "I‘m building an application on theAutonomous View pattern," but you‘ll recognize it in a heartbeat.  The autonomous view is a single piece of code that encapsulates both presentation and screen behavior in one single lump of code.  In WinForms the autonomous view is characterized by completely self-contained Form and UserControl‘s.  While it‘s perfectly suitable for simpler screens, it can present some maintainability issues for screens of even moderate complexity because of the mixture of concerns.  The biggest issue for me is that the code in an autonomous view is significantly harder to unit test than code in POCO classes.  It‘s also potentially harder to understand because so many concerns are intermingled with the WinForms machinery.  To some degree you can instantiate WinForms classes in memory and run unit tests against this code with or even withoutNUnitForms, but it‘s often much more trouble than it‘s worth.
Build your own CAB Part #2 - The Humble Dialog Box
When last we left our hero, D‘Artagnan was chasing the evil Lady de Winter across the breadth of France trying to intercept her on her dastardly mission when he found himself beset by disparate responsibilities within the tight confines of a single autonomous view with no room for sword play.  D‘Artagnan, being a perspicacious young man, quickly sees a way to separate the numerous concerns he‘s facing by opening his attack with...
The Humble Dialog Box
I‘d say the very first concept to grasp in software design is separation of concerns.  Divide and conquer.  Eat the elephant one bite at a time.  Learning how to decompose a bigger problem into a series of approachable goals.  I‘d rather work serially on a screen by completing one simple task before moving onto the next instead of working with all aspects of a screen in parallel.  Division of responsibility for easier programming is a major consideration by itself, but there‘s another piece of motivation almost as important.  Because user interface code can be very complex to debug and is prone to change based on user experience, I really, really want to extend granular unit testing with automated tests as far into the presentation layer as I possibly can.
Traditionally, user interface code has appeared to repel all but the most serious attempts at test automation.  Automated testing against UI code was just flat out deemed too much work for the gain.  That equation has changed over the last several years with the rise of architectures inspired by The Humble Dialog Box from Michael Feathers.
Here‘s the canonical example of the Humble Dialog Box I use to explain the concept.  Say you have a user screen for some sort of data entry.  You have a requirement that reads something like:
If the user attempts to close the XYZ screen without saving any outstanding changes, a message box is displayed to warn the user that they are discarding changes.  If the user wishes to retain the outstanding work, do not close the screen.  The message box should not be shown if the data has not been changed.
It‘s not that complex of a requirement really, but it‘s the kind of thing that makes a user interface client easy and convenient to use.  We want this code to work.  The code for it might look like this:
private void ArrogantView_Closing(object sender, CancelEventArgs e)
{
// Let‘s not worry for now about how we figure out the screen has unsaved data
if (isDirty())
{
bool canClose = MessageBox.Show("Ok to discard changes or cancel to keep working") == DialogResult.OK;
e.Cancel = !canClose;
}
}
That code really isn‘t that complex, but let‘s think about how we could automate a test for this requirement to run within our regression test suite.  That little bitty call to MessageBox.Show() and the modal dialog box that results is a serious pain to deal with in an automated test (it is possible, and I‘ve done it before, but I‘d strongly recommend you keep reading before you run off and try it).  Observing the UI getting closed or not is also tricky, but I think the worst part is that to test this logic you have to fire up the UI, navigate to the screen, change some data on the screen, then trigger the close screen request.  That‘s a lot of work just to get to the point at which you‘re exercising the code you care about.
Now, let‘s rewrite this feature as a "Humble" view, but before I show the new code, let‘s talk about the Humble view philosophy.  The first thing to do is to put the view on a diet.  Any code in a WinForms UserControl or Form is almost automatically harder to test than it would be in a POCO.  A Humble view should be the smallest possible wrapper around the actual presentation code.  Going farther, I don‘t want implementation details of the view mechanics to leak into other areas of the code, so I want to hide the View behind a POCO-ish interface.  All that being said, the abstracted interface for our View could look like:
public interface IHumbleView
{
bool IsDirty();
bool AskUserToDiscardChanges();
void Close();
}
The view is also "passive," meaning that it doesn‘t really take any actions on its own without some sort of stimulus from outside the view.  I‘ll discuss handling user events in depth in a later chapter, but for now let‘s just say that the view simply relays user input events to somewhere else with little or no interpretation.
One of the goals of a Humble view is to separate responsibilities.  As in most designs, we want to assign different responsibilities to different areas of the code.  In this case, we want to pull behavioral logic out of the view and into non-visual classes.  If we put the view itself on a diet and pull out anything that isn‘t directly related to presentation, that extra code that implements things like behavior and authorization rules has to go somewhere.  In this case we‘re going to move those responsibilities into a Presenter class:
public class OverseerPresenter
{
private readonly IHumbleView _view;
public OverseerPresenter(IHumbleView view)
{
_view = view;
}
public void Close()
{
bool canClose = true;
if (_view.IsDirty())
{
canClose = _view.AskUserToDiscardChanges();
}
if (canClose)
{
_view.Close();
}
}
}
In particular, look at the Close() method.  Some user event causes a call to the OverseerPresenter.Close() method.  Inside this method we check the "dirty" state of the IHumbleView member and potentially ask the user to discard changes before proceeding to close the actual view.  It‘s just about the exact same code, only now we can write an automated unit test to express this logic -- with just a little help from our good friend RhinoMocks.
[TestFixture]
public class OverseerPresenterTester
{
[Test]
public void CloseTheScreenWhenTheScreenIsNotDirty()
{
MockRepository mocks = new MockRepository();
IHumbleView view = mocks.CreateMock();
Expect.Call(view.IsDirty()).Return(false);
view.Close();
mocks.ReplayAll();
OverseerPresenter presenter = new OverseerPresenter(view);
presenter.Close();
mocks.VerifyAll();
}
[Test]
public void CloseTheScreenWhenTheScreenIsDirtyAndTheUserDecidesToDiscardTheChanges()
{
MockRepository mocks = new MockRepository();
IHumbleView view = mocks.CreateMock();
Expect.Call(view.IsDirty()).Return(true);
Expect.Call(view.AskUserToDiscardChanges()).Return(true);
view.Close();
mocks.ReplayAll();
OverseerPresenter presenter = new OverseerPresenter(view);
presenter.Close();
mocks.VerifyAll();
}
[Test]
public void CloseTheScreenWhenTheScreenIsDirtyAndTheUserDecidesNOTToDiscardTheChanges()
{
MockRepository mocks = new MockRepository();
IHumbleView view = mocks.CreateMock();
Expect.Call(view.IsDirty()).Return(true);
Expect.Call(view.AskUserToDiscardChanges()).Return(false);
// No call should be made to view.Close()
// view.Close();
mocks.ReplayAll();
OverseerPresenter presenter = new OverseerPresenter(view);
presenter.Close();
mocks.VerifyAll();
}
}
So I know what you might be thinking, what have I really gained here?  Let me try to answer this:
Orthogonality.  We‘ve moved behavioral logic out of the actual view.  We can change the presentation or the behavior independently.  That is a big deal.  The screen behavior is easier to understand.  I‘m going to argue that this is a case ofReg Braithwaite‘s Signal to Noise Ratio in code (basically, expressing the intent of the code with little code that isn‘t directly related to the intent).  When I want to understand the screen behavior, that behavior is the only signal I care about.  Seeing (object sender, CancelEventArgs e) everywhere in the middle of the behavioral code is noise.  The converse is true as well when I‘m working on the presentation itself. The screen behavior is easier to test and modify.  That‘s enough by itself to justify the Humble View style.  What if this closing behavior changes tomorrow with a requirement to set a user preference to never ask users to discard changes?  If I‘m working in a Humble View style, I can probably make that screen behavior change completely, including unit tests, in the Presenter class by itself without ever having to fire up the user interface until the very last sanity check.  Verifying little behavior changes with NUnit is a far, far tighter feedback cycle than doing the save verification by firing up the user interface and doing the manual input steps necessary to exercise the functionality.  Tight feedback cycles == productivity.  By extending the reach of granular and automated unit tests farther into the potentially complex user interface code, we can drastically slow down the rate of screen defects getting through to the testers.  If nothing else, we can knock down all the common uses of the user interface quickly through tests to give the testers more time to break the application with edge cases and exploratory testing.
An astute reader will note that we didn‘t write any unit tests for the View.  I‘ll show an example in later chapters of testing the View itself, but the philosophy in general is to make the hard to test view code so simple as to be reliably verified by inspection alone.  I.e., you should make the View code so simple that it‘s almost hard to screw it up.
A Taxonomy of Humble Views
Arguably the first Humble View is the original Model View Controller architecture handed down, as basically everything good in software developer seems to be, from the Smalltalk community.  As I‘ve mentioned before, you can read about the evolution of theModel View Controller (MVC) pattern and the formulation of the Model View Presenter (MVP) patterns that we‘re mostly talking about in this series as user interface toolkits changed.
D‘Artagnan‘s masterful implementation of the Humble Dialog Box vanquishes his foes, but he knows he‘ll need trusted companions now that the evil Lady de Winter surely knows he is in pursuit.  Fortunately, D‘Artagnan‘s trusty three companions are riding hard to join him.  D‘Artagnan smiles to himself and imagines his friends coming around the bend in the road:
Supervising Controller -- I‘m here to help the View with the harder cases! Passive View -- I only do what I‘m told Presentation Model -- Just do what I do
D‘Artagnan sees dust rising in the air, a traveler is coming...
Build your own CAB Part #3 - The Supervising Controller Pattern
When last we left D‘Artagnan he had just concluded a successful duel with a number of screen concerns by dividing them with a masterful usage of the Humble Dialog Box.  As D‘Artagnan strives to regain his breathe, he‘s heartened by the appearance of his three doughty companions Athos, Aramis, and Porthos.  As the four friends sit down in a shady spot besides the road for a fine meal of delicacies (unknowingly donated by a noblewoman of Athos‘ acquaintance), D‘Artagnan describes their predicament when they manage to corner the Lady de Winter and her host of minions.
A Shipping Screen
Let‘s imagine that you need to build a little screen to allow a user to configure the shipping options for some sort of electronic order that looks something like this screenshot below:

The user first needs to select the state or province (since this was for a talk in Canada, I thought it would be nice to let our Canuck neighbors to the north use the app too) that is the destination of the shipment.  Not every shipping vendor can ship to every destination, so we should modify the contents of the shipping vendor dropdown to reflect the destination.  Likewise, a change in the selected shipping vendor will also cascade down to the list of shipping options (think Overnight, 2 business day, parcel, etc.).  Some, but not all, shipping options allow the customer to purchase insurance in case of loss or require a signature at the destination for guaranteed delivery.  Finally, the cost of the shipment should be recalculated and displayed on the screen anytime the shipping selections are changed.
I can spot a couple different responsibilities in just that paragraph, plus a couple more down the line when it‘s time to actually submit the shipment.  Even this little screen has enough complexity in it that I wouldn‘t want to bundle all of the responsibilities into a single autonomous view.  So let‘s enumerate just the responsibilities from that paragraph and start thinking about how to assign these responsibilities to different classes.
Display and capture the currently selected shipment options Respond to user events like selecting a value in the ComboBox‘s Fetching the list of states Fetching the list of shipping vendors for a given state or province Fetching the list of options for a given state/province and vendor Changing the dropdown lists Enabling and disabling the checkbox‘s for purchasing insurance and requiring a signature Calculate the shipping cost for the selected options Update the cost textbox whenever the shipment options change
That‘s a fair amount of behavior and business logic for one little screen.  We know that we probably want to employ some sort of Humble View approach to split out some of the responsibilities from the Form class and into POCO classes that are easier to test.  I‘m going to show three sample solutions of the shipping screen, each using a bit different approach to assigning responsibilities.
Interlude
The four friends mull over the looming fight with the forces of Lady de Winter as they finish off a fine cheese produced from the endless saddlebags of Aramis‘s manservant.  D‘Artagnan  poses this question to the older musketeers:  "When I‘m beset by a multitude of concerns in a single screen, what technique should I use to best each concern in turn?"  The three older musketeers ponder the question raised by their younger companion.  Finally, Athos speaks up.  "I would not concern myself with the simpler responsibilities of a screen.  I would first seek to eliminate the more complicated screen responsibilities by employing..."
The Supervising Controller
The goal of theSupervising Controller variant of Model View Presenter is to remove the more complicated screen scenarios that deserve more unit testing attention out of the view and into a separate Presenter class.  The Supervising Controller strategy takes advantage of the data binding support in WinForms for simple screen synchronization.  To that end, we‘ll create a simple class called Shipment that will be our Model in the MVP triad.
public class Shipment : INotifyPropertyChanged
{
private string _stateOrProvince;
private string _vendor;
private string _shippingOption;
private bool _purchaseInsurance;
private bool _requireSignature;
private double _cost;
public string StateOrProvince
{
get { return _stateOrProvince; }
set
{
_stateOrProvince = value;
fireChanged("StateOrProvince");
}
}
public string Vendor
{
get { return _vendor; }
set
{
_vendor = value;
fireChanged("Vendor");
}
}
// And the rest of the properties...
}
The View itself simply has a setter that takes in a Shipment object and starts up the data binding.
public Shipment Shipment
{
set
{
// start up the data binding stuff
}
}
I‘ll talk about options for the Model in depth in a later post, but for now, let‘s say that Shipment is just a dumb batch of getters and setters.  Since I can‘t stand writing INotifyPropertyChanged interface implementations by hand, you‘ll probably want to codegen these Model classes -- again giving me even more reasons to keep the Shipment class dumb.
We‘ve taken care of the actual presentation of the shipment data, so let‘s move on to more responsibilities.  There‘s no possible way that a screen should know how to calculate the shipping costs, and probably shouldn‘t know how to fetch the data for the dropdown selections.  Deciding whether or not a shipper and shipping option allows a user to purchase insurance or require a signature on receipt is business logic for the real domain logic classes, not screen logic that belongs in the screen.  Let‘s not particularly worry about how this stuff is implemented right now.  Let‘s just define an interface for all of this functionality (and aData Transfer Object as well).
public class DeliveryOptions
{
private bool _purchaseInsuranceEnabled;
private bool _requireSignatureEnabled;
public bool PurchaseInsuranceEnabled
{
get { return _purchaseInsuranceEnabled; }
set { _purchaseInsuranceEnabled = value; }
}
public bool RequireSignatureEnabled
{
get { return _requireSignatureEnabled; }
set { _requireSignatureEnabled = value; }
}
}
public interface IShippingService
{
string[] GetLocations();
string[] GetShippingVendorsForLocation(string location);
string[] GetShippingOptions(Shipment shipment);
void CalculateCost(Shipment shipment);
DeliveryOptions GetDeliveryOptions(Shipment shipment);
}
The IShippingService interface works on our Shipment class that we‘re binding to in the actual screen, as opposed to exposing primitive arguments.  When I was writing the sample code it seemed to me to be a simple way of interacting with the service because it cuts down on any data transformations between screen and service.  The CalculateCost(Shipment) method would also write the cost back to the Shipment object, cascading a corresponding change to the screen as the data binding updates the screen based on changes to Shipment.  It‘s probably worth noting that this IShippingService could just be a Facade class over the business logic specifically created for easier consumption by the user interface.  In the next chapter I‘ll take a different approach that exposes the underlying Domain Model classes for the shipping system.
At this point we‘re largely left with just responsibilities for changing the dropdown options and mediating between the View and the IShippingService.  That‘s where the ShippingScreenPresenter finally comes in to provide the missing functionality that goes beyond simple data binding, as well as coordinating user actions with the IShippingService.
public class ShippingScreenPresenter
{
private readonly IShippingScreen _view;
private readonly IShippingService _service;
private Shipment _shipment;
public ShippingScreenPresenter(IShippingScreen view, IShippingService service)
{
_view = view;
_service = service;
_shipment = new Shipment();
// Since we‘re got the INotifyPropertyChanged interface on Shipment,
// we might as well use it to trigger updates to the Cost
_shipment.PropertyChanged += new PropertyChangedEventHandler(_shipment_PropertyChanged);
}
private void _shipment_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
_service.CalculateCost(_shipment);
}
public Shipment Shipment
{
get { return _shipment; }
}
public void Start()
{
_view.Shipment = _shipment;
}
// React to the user selecting a new destination
public void LocationChanged()
{
_view.Vendors = _service.GetShippingVendorsForLocation(_shipment.StateOrProvince);
}
// React to the user changing the Vendor
public void VendorChanged()
{
_view.ShippingOptions = _service.GetShippingOptions(_shipment);
}
// React to the user changing the Shipping Option
public void ShippingOptionChanged()
{
DeliveryOptions options = _service.GetDeliveryOptions(_shipment);
_view.InsuranceEnabled = options.PurchaseInsuranceEnabled;
_view.SignatureEnabled = options.RequireSignatureEnabled;
}
}
Since I‘ve been claiming that this style of user interface structure improves the testability of the screen as a whole, let‘s take a look at what the unit tests might look like.  Here‘s the unit test for correctly enabling or disabling the insurance and signature checkbox‘s on the shipping screen after the shipping option changes:
[Test]
public void EnableOrDisableTheInsuranceAndSignatureCheckboxesWhenShippingOptionChanges()
{
MockRepository mocks = new MockRepository();
IShippingService service = mocks.CreateMock();
IShippingScreen screen = mocks.CreateMock();
ShippingScreenPresenter presenter = new ShippingScreenPresenter(screen, service);
// Setting up the expected set of Delivery options
DeliveryOptions deliveryOptions = new DeliveryOptions();
deliveryOptions.PurchaseInsuranceEnabled = true;
deliveryOptions.RequireSignatureEnabled = false;
// Set up the expectations for coordinating both
// the service and the view
Expect.Call(service.GetDeliveryOptions(presenter.Shipment))
.Return(deliveryOptions);
screen.InsuranceEnabled = deliveryOptions.PurchaseInsuranceEnabled;
screen.SignatureEnabled = deliveryOptions.RequireSignatureEnabled;
// Perform the work and check the expectations
mocks.ReplayAll();
presenter.ShippingOptionChanged();
mocks.VerifyAll();
}
The first thing you might notice is that this is definitely aninteraction based unit test.  That‘s not surprising since one of the primary duties of a Presenter is to mediate between the services and view.  In development with Test Driven Development / Behavior Driven Development, it‘s often advantageous to separate the responsibility for performing an action away from the decision to perform that action.  In this case, the real View enables the insurance and signature checkboxes when the Supervising Presenter tells it to enable or disable the checkboxes.  In other words, the Supervising Presenter is the mostly immobile queen bee, and the View is the mobile, but relatively brainless, worker bee.  In unit tests like the one above, we‘re largely testing that the Presenter is sending the correct signals to the View and service interfaces.
For another example, here‘s a unit test for recalculating the shipment cost as the selected shipping options change:
[Test]
public void UpdateTheCostWheneverTheShipmentChanges()
{
MockRepository mocks = new MockRepository();
IShippingService service = mocks.CreateMock();
IShippingScreen screen = mocks.CreateMock();
ShippingScreenPresenter presenter = new ShippingScreenPresenter(screen, service);
service.CalculateCost(presenter.Shipment);
mocks.ReplayAll();
presenter.Shipment.Vendor = "a different vendor";
mocks.VerifyAll();
}
That wasn‘t that bad, now was it?  But wait, you ask.  Where‘s the actual logic for calculating the shipment cost?  For right now I‘m just worried about the wiring of the screen itself.  Yes, this unit test covers very little ground, and it‘s not a "real" test, but I‘ve created some level of trust that this particular linkage in the code does work.  I can now turn my back on the screen itself and test the actual ShippingService by simply pushing in Shipment objects and checking that the Cost field is correctly updated.  Not one single line of the shipping screen code needs to be present for any of that logic to be tested.  I hope it‘s needless to say that there really shouldn‘t be any leakage of domain logic into the screen code.  Real domain logic in views is just about the fastest way possible to create an utterly unmaintainable system.
Interlude
The four friends pondered Athos‘s solution in quiet contemplation in the state of contentment that only follows a fine meal.  "Wait," exclaims D‘Artagnan, "You haven‘t told us how the View talks to the Presenter, and who creates who!  How should this work?"  Athos simply shakes his head and says "it‘s a long ride to Dunkirk, we‘ll talk more of this on the road."  (as in, I‘ll get there, just give me a couple more chapters - Jeremy).
How I Prefer to Work
Personally, I wouldn‘t order the work quite the way I showed above.  I like to start with either a screen mockup or maybe even the actual view.  If you start with the actual concrete view class, don‘t wire it up yet, and whatever you do, don‘t automatically implement the intended "IView" interface until you‘re done with the Presenter.  Sometimes I‘ll start by taking some notes or sketching out some UML or CRC models about the screen scenarios.  My next step is to encode the behavioral aspect of the screen in the Presenter.  I use RhinoMocks in place of both the View and whatever service interfaces the Presenter needs.  As much as possible, I like to define the methods and interactions of the Presenter with the services and view in a unit test body and just let ReSharper generate the methods on the dependencies.  Since we‘re strictly dealing with interfaces here, we don‘t have to break our flow with the Presenter to implement the services and view just yet.  As soon as the Presenter itself is fully fleshed out, I implement the IView interface on the real View and create an implementation for any of the service dependencies.
This probably isn‘t realistic for complex screens, but at least on simple screens it should become quite ordinary for a screen to just work the first time it‘s run in the UI -- assuming you unit tested all of the pieces individually.
Summary
I‘d bet that Supervising Controller is probably the most commonly used Humble View architecture, but I don‘t have any figures at hand on that.  It still allows you to use the design time support to layout controls and even configure the data binding with the visual tools (but we‘re going to talk about options to data binding later).  My current project is using Supervising Controller (sans data binding), and I think it‘s largely where the sweet spot is.  I will use the other options at times though, and there are a lot of different variations on each of the other Humble Views, so we‘re not done yet.
Is this really worth doing?  I say yes, otherwise I wouldn‘t be doing it.  Let me put it to you this way, on the first project I used the Humble View (Passive View actually) approach, we saw a strong correlation between the bug count per screen and the unit test coverage for the code on that screen.  Screens that were driven with unit tests on the Presenter had many fewer behavioral bugs.  I‘m talking it even farther on my current project by adding NUnitForms tests on the View to Presenter interaction, plus Fit tests on the actual screen behavior.
If you‘re not a fan of interaction based testing, and using mock objects gives you an allergic reaction, don‘t worry.  I‘ve got stuff for you too coming up.
Conclusion
The four friends pondered the wisdom of Athos‘ approach while drinking their way through the rest of the wine from D‘Artagnan‘s packs.  Suddenly, mighty Porthos clears his throat and...
Build your own CAB Part #4 - The Passive View
When last we left our brave companions, between courses of cheese and fine wine, Athos was sharing his strategy for dividing screen responsibilities by employing the Supervising Controller pattern.  Mighty Porthos suddenly cleared his throat and exclaimed "since I am the strongest man in all of France, I would face my opponents a different way.  Because the View itself is the trickiest piece of code to test and maintain, I would squeeze the View with great force until the only thing left inside the View is a mere skeleton of presentation logic.  I will render the Lady de Winter‘s greatest warrior a mere...
Passive View
Last time we looked at a small screen that allows a user to select options for configuring the shipment options for some sort of online order.  We examined a sample approach utilizing the Supervising Controller variant of Model View Presenter that left the View in charge of simple screen synchronization while utilizing an external Presenter class to handle more complex behavior and all communication with the rest of the system.  This time around we‘re going to build the exact same system, but use thePassive View variant of Model View Presenter.
It‘s probably easiest to explain Passive View by first explaining how it‘s different than Supervising Controller.  The goal of the Passive View is to maximize the ability to automate testing of the screen, and that means taking as much as possible out of the hard to test View code and moving it to the Presenter.  For that reason, the biggest difference is the reduced role of the View -- even from the already slimmed down View attached to a Supervising Controller.  The Presenter/Controller is responsible for all screen synchronization.  The View in Passive View is an extremely thin wrapper around the presentation details with next to no behavior of its own.  The view probably doesn‘t even know about the Model classes.  To start the Passive View solution, let‘s look first at the interface for IShippingScreen:
public interface IShippingScreen
{
string[] ShippingOptions { set; }
string[] Vendors { set; }
bool InsuranceEnabled { set; }
bool SignatureEnabled { set; }
string StateOrProvince { get; set;}
string Vendor { get; set;}
string ShippingOption { get; set;}
bool PurchaseInsurance { get; set;}
bool RequireSignature { get; set;}
double Cost { get; set;}
}
As you can probably guess from this interface alone, the View becomes simplistic.  The Presenter is now responsible for telling the view what piece of information to put into each UI widget.  The concrete View is going to end up looking something like this:
public partial class ShippingScreen : Form, IShippingScreen
{
public ShippingScreen()
{
InitializeComponent();
}
public string ShippingOption
{
get { return shippingOptionField.SelectedText; }
set { shippingOptionField.SelectedText = value; }
}
public bool PurchaseInsurance
{
get { return purchaseField.Checked; }
set { purchaseField.Checked = true; }
}
// Who sees a problem here?
public double Cost
{
get { return double.Parse(costField.Text); }
set { costField.Text = value.ToString(); }
}
// Stuff that we don‘t care about
#region Stuff that we don‘t care about
#endregion
}
At this point, the view is as dumb as we can possibly make it.  It should be nearly trivial to verify the functioning of the View code by simple inspection -- for the most part anyway.  We could easily decide to forgo testing the actual View itself at this point and judge that to be a perfectly acceptable compromise.
The Presenter is now more complicated because it‘s taking on the additional responsibility for synchronizing data between the screen and the Domain Model.  In this case it‘s making a one to one transference of properties from the screen elements to the properties of the Shipment class.
private Shipment createShipmentFromScreen()
{
Shipment shipment = new Shipment();
shipment.PurchaseInsurance = _screen.PurchaseInsurance;
shipment.StateOrProvince = _screen.StateOrProvince;
// so on, and so forth
return shipment;
}
For a small screen, that‘s not that bad.  In reality, I generally use Passive View for small screens like login screens.  I do find the screen synchronization to be a chore.  Then again, think about the case of a screen that serves to display and edit an aggregate object structure with multiple levels of hierarchical data.  Data binding works best with "flat" objects, so you‘ve got to do something.  In my mind, sacrificing the structure of the business domain to fit the user interface tooling is mostly a poor compromise.  To have the best of both worlds you can either create a wrapping object to provide a "flattened" view of the object hierarchy to allow data binding to work, or skip that and use Passive View to have better control over the screen synchronization.
What is cool about Passive View, besides the extra testability, is a further set of insulation between the presentation technology and the business and service layers of the application. When I built the Supervising Controller approach, I deliberately used an object specifically built for the data binding and hid the "real" domain behind IShippingService.  This time around, let‘s let the Presenter work with the "real" domain classes somewhat.  That being said, ShippingScreenPresenter will now interact with an IShipper class to get at the business rules for a particular shipping option.
public interface IShipper
{
bool AcceptsInsurance { get;}
bool CanRequireInsurance { get;}
string[] Options { get;}
string Description { get;}
bool CanCaptureSignature { get; }
double CalculateCost(Shipment shipment);
}
Of course, we‘ve got to find the correct IShipper in the first place.  For that, we‘ll use aRepository:
public interface IShipperRepository
{
IShipper[] GetShippersForLocation(string location);
IShipper FindShipper(string shipperName);
}
Even more so this time, the ShippingScreenPresenter is largely a Mediator between the interfaces exposed by IShippingScreen, IShipper, and IShippingRepository.  The screen synchronization can be more work inside the presenter, but I think you can get by with less abstraction of the rest of the application.  The ShippingScreenPresenter might look like this:
public class ShippingScreenPresenter
{
private readonly IShippingScreen _screen;
private readonly IShipperRepository _repository;
private IShipper _shipper;
public ShippingScreenPresenter(IShippingScreen screen, IShipperRepository repository)
{
_screen = screen;
_repository = repository;
}
public void ShipperSelected()
{
_shipper = _repository.FindShipper(_screen.Vendor);
_screen.ShippingOptions = _shipper.Options;
_screen.InsuranceEnabled = _shipper.CanRequireInsurance;
_screen.SignatureEnabled = _shipper.CanCaptureSignature;
}
private Shipment createShipmentFromScreen()
{
Shipment shipment = new Shipment();
shipment.PurchaseInsurance = _screen.PurchaseInsurance;
shipment.StateOrProvince = _screen.StateOrProvince;
// so on, and so forth
return shipment;
}
public void OptionsChanged()
{
Shipment shipment = createShipmentFromScreen();
_screen.Cost = _shipper.CalculateCost(shipment);
}
}
Needless to say, using the Passive View pretty well demands anInteraction Testing style of unit tests with lots of mock objects.  If you don‘t grok RhinoMocks, Passive View might not be for you.  Supervising Controller is a definite alternative, but in a later section I‘ll take a look at the Presentation Model pattern for a state-based style of unit testing.
Interlude
Young D‘Artagnan looks puzzled.  He finally asks his older friends "Wouldn‘t that make the communication between the Presenter and View very chatty?  And what‘s to stop the Presenter from becoming just as convoluted as an Autonomous View?"  Porthos snorts and exclaims "You are a perspicacious lad!  I would not stop with crushing the View into submission.  I will use my superior strength to crush the Presenter until it only contains a single, cohesive responsibility!"
Summary
I used Passive View quite extensively on my first WinForms project in 2004.  Overall, the experience hooked me for life on using Humble Dialog Box design philosophies for building fat clients.  It became routine for screens to work on the very first attempt to run new screen features -- assuming that you really did unit test the individual pieces first.  We also so another noticeable trend, screens that were fatter with more logic and less unit test coverage generated alarmingly more bugs and took much more time to debug.
I mentioned that the screen synchronization can become a chore.  The presenter potentially picks up more responsibilities for screen synchronization and state like "IsDirty" checks.  The downside of Passive View is a chatty interface between View and Presenter.  I wrote an article early last year detailing myBest and Worst Practices for Mock Objects.  Most of the advice for what not to do with Mock objects came from that same project that we used Passive View.  My advice is to watch the size of the Presenter.  If it gets too big, split up responsibilities.  Maybe you take screen synchronization, IsDirty logic, and maybe validation and put it in some kind of "inner" presenter.  The "Inner" presenter talks to the View itself.  The "Outer" presenter talks to the "Inner" presenter and the outside world.
One way to detect a need for this Inner/Outer presenter case is to watch your unit tests.  If you ever find yourself writing an uncomfortable number of mock object expectations in any one test, you‘re probably violating theSingle Responsibility Principle (SRP).  If you find yourself setting up mock object expectations for something that‘s barely relevant to the subject of the unit test, you almost automatically split the class under test into multiple classes.  One of the best design tricks you can apply is to continuously move your design closer and closer to SRP.
Conclusion
The four friends finished their repast and sat around the fire, sated from the provisions generously supplied by a minor noblewoman of Atho‘s acquaintance.  Aramis, who the companions know is the craftiest of the four friends, speaks up:  "slaying a View of many responsibilities with the sharp edge of a mock object is a fine thing, but I think that we can use our wits to fool the screen into  subservience to state based testing by employing the Presentation Model to..."
Build your own CAB Part #5 - The Presentation Model
Our four friends are crafting a strategy for the inevitable and highly anticipated clash with the minions of the Lady de Winter.  Mighty Porthos has just finished a long oration about hisPassive View approach to creating maintainable WinForms screens.  The crafty Aramis has started his own oratory on his preferred approach to avoid so much Interaction Based Testing by utilizing...
The Presentation Model
ThePresentation Model differs from the two Model View Presenter approaches (Supervising Controller andPassive View) by combining the "M" and the "P" into a single class.  This single Presentation Model class both contains the state of the screen and implements the behavior of the screen.  Compared to the Supervising Controller, Presentation Model is more complex in that it also implements the state of the screen, but also less complex because the state synchronization is almost entirely the responsibility of the View itself.  Instead of a Presenter directing the View to change the state of the screen, the Presentation Model simply changes its own state and depends on Data Binding (or an equivalent) to update the screen accordingly.
Let‘s jump right into our third and final implementation of theShipping Screen.  As I stated before, the View will use data binding to bind its screen elements to the public properties on the new ScreenPresentationModel class.
public partial class ShippingScreen : Form
{
public ShippingScreen()
{
InitializeComponent();
}
public void Bind(ShippingPresentationModel model)
{
shipmentBindingSource.DataSource = model;
}
}
I‘ll spare you the rest of the data binding setup code, and besides, that‘s covered in other literature to a vastly greater degree than Presentation Model.  Besides which, I‘ve barely worked with data binding and you‘ve probably guessed correctly that I‘m more than a little biased against it.
So far we haven‘t seen anything that different from Supervising Controller, but when you use the Presentation Model approach you‘re probably exploiting the fact that data binding in WinForms can also bind to the "Visible" and "Enabled" properties of controls and not just the value.  In the case of the Shipping screen, we‘ll bind the "Enabled" properties of the checkbox‘s for selecting insurance and requiring a signature to properties on the ShippingPresentationModel shown below.
public bool InsuranceEnabled
{
get { return _insuranceEnabled; }
set { _insuranceEnabled = value; }
}
public bool SignatureEnabled
{
get { return _signatureEnabled; }
set { _signatureEnabled = value; }
}
public string Vendor
{
get { return _vendor; }
set
{
_vendor = value;
fireChanged("Vendor");
DeliveryOptions options = _service.GetDeliveryOptions(this);
InsuranceEnabled = options.PurchaseInsuranceEnabled;
SignatureEnabled = options.RequireSignatureEnabled;
}
}
In the above code, anytime a user selects a different shipping vendor the data binding will call the setter for Vendor on ShippingPresentationModel, causing a recalculation of the InsuranceEnabled and SignatureEnabled properties, which finally causes the two checkbox‘s to be either enabled or disabled depending upon the shipping vendor selected.  All because a little bug went kachooo!
The communication between View and the Presentation Model is relatively simple, the View simply sets properties on the PresentationModel class and cascading actions are triggered in the setters.  I‘ve purposely put off talking about View to Presenter communication, but let‘s just say that this aspect of the Presentation Model is simpler than either Supervising Controller or Passive View.
One last example of the ShippingPresentationModel.  There are three or four factors that influence the cost of the shipment.  If any of these screen elements change, the cost needs to reevaluated.  With Presentation Model, I just capture all change events inside the setters, so the trigger to reevaluate the shipping cost is something like this:
public string ShippingOption
{
get { return _shippingOption; }
set
{
_shippingOption = value;
fireChanged("ShippingOption");
_service.CalculateCost(this);
}
}
public bool PurchaseInsurance
{
get { return _purchaseInsurance; }
set
{
_purchaseInsurance = value;
fireChanged("PurchaseInsurance");
_service.CalculateCost(this);
}
}
public bool RequireSignature
{
get { return _requireSignature; }
set
{
_requireSignature = value;
fireChanged("RequireSignature");
_service.CalculateCost(this);
}
}
I simply make a call to IShippingService.CalculateCost(IShipment) anytime a property changes that impacts the shipping calculation.  For convenience sake, I made ShippingPresentationModel implement a common IShipment interface that is consumed by IShippingService, if you‘re wondering where in the world the "this" parameter was coming from.  I‘m assuming that the IShippingService will itself set the IShipment.Cost property.  The signatures for IShippingService still looks like this:
public interface IShippingService
{
string[] GetLocations();
string[] GetShippingVendorsForLocation(string location);
string[] GetShippingOptions(IShipment shipment);
void CalculateCost(IShipment shipment);
DeliveryOptions GetDeliveryOptions(IShipment shipment);
}
State Based Unit Testing
The biggest difference to me in using Presentation Model versus one of the MVP patterns is the shift to state based testing inside of our xUnit tests.  I‘m more or less a "mockist" I guess, but I‘ve worked with more than a few people who‘ve had almost allergic reactions to using mock objects.  If you‘re one of those people, don‘t worry, you‘re not out of luck because you can do more or less state based testing with Presentation Model.  Here‘s an example of what I mean (even though out of pure contrariness I‘m using RhinoMocks to create my stub):
[Test]
public void ResetTheShippingOptionsWhenTheStateOrProvinceIsChanged()
{
// We‘re going to test ShippingPresentationModel in a state-based manner
// I‘m using RhinoMocks to create the stub just because
//   a.)  It‘s easy
//   b.)  I hate cluttering up the code with static mocks and stubs if
//        I don‘t have to.
// You might note that I‘m not even bothering to call mocks.VerifyAll()
MockRepository mocks = new MockRepository();
IShippingService service = mocks.CreateMock();
ShippingPresentationModel model = new ShippingPresentationModel(service);
string[] theOptions = new string[]{"Option 1", "Option 2", "Option 3"};
Expect.Call(service.GetDeliveryOptions(model)).Return(theOptions).Repeat.Any();
mocks.ReplayAll();
// We need to verify that the model starts with a zero array string
Assert.AreEqual(0, model.ShippingOptions.Length);
// I‘m not sure I‘d bother testing the raising of the PropertyChanged event,
// or at least do it in another test.
bool propertyWasCalled = false;
model.PropertyChanged += delegate (object sender, System.ComponentModel.PropertyChangedEventArgs e)
{
propertyWasCalled = e.PropertyName == "ShippingOptions";
};
model.StateOrProvince = "TX";
// Check that the state of the model changed
Assert.AreEqual(theOptions, model.ShippingOptions);
// And while we‘re at it, let‘s check that the PropertyNotified event was called
Assert.IsTrue(propertyWasCalled);
}
All I‘m testing here is that the ShippingPresentationModel gets a list of Shipping Options whenever the StateOrProvince property is changed, then resets its ShippingOptions property.  I‘m not real wild about it, but I also showed using an anonymous delegate to check that the PropertyChanged event was fired for "ShippingOptions."  To recap, the expected sequence of events is:
The user selects a value in the State or Province select box. Data binding in the view sets the StateOrProvince property on ShippingPresentationModel.  Since the View is just talking directly to getters and setters, we really don‘t need the View involved in this unit test at all. In the setter for StateOrProvince, the ShippingPresentationModel should find the ShippingOptions for the selected state or province and set it‘s internal value for ShippingOptions which... Fires the PropertyChanged event for "ShippingOptions" which directs the magical data binding support to fill the dropdown list for Shipping Options with new values (which I didn‘t show because it‘s documented very well on MSDN).
Whew.  The code that implements this test above is much simpler:
public string StateOrProvince
{
get { return _stateOrProvince; }
set
{
_stateOrProvince = value;
// Whenever this property changes, we need to reset the
// ShippingOptions to match the StateOrProvince
ShippingOptions = _service.GetShippingOptions(this);
fireChanged("StateOrProvince");
}
}
public string[] ShippingOptions
{
get { return _shippingOptions; }
set
{
_shippingOptions = value;
fireChanged("ShippingOptions");
}
}
Summary
The Presentation Model is another example of a Humble View.  It largely differs from the Model View Presenter patterns by combining the Model and Presenter into a single class.  It‘s important to note that the Presentation Model most likely encapsulates the actual application model, and it‘s definitely part of the user interface rather than a domain model class implementing pure business logic.  While it does a great job isolating behavior from the View and exposing the behavior in a way that allows for state based testing, you might find yourself getting annoyed at all the delegation that has to take place between the Presentation Model class and the inner application model.  Then again, a buffer between the user interface and the rest of the application might just be a good thing.
Honestly, I haven‘t used this pattern but a time or two.  The largest implementation I‘ve seen was actually a Java Swing client where it was used quite effectively.
I do have an example from StoryTeller that I will probably use in the posts on creating an Application Shell where I use Presentation Model as a kind of state machine to synchronize menu state as the screen mode changes.  I‘m leaving it out now for the sake of brevity (and my impending bedtime).
Other Resources
I think Presentation Model is another name for theModel/View/ViewModel pattern being promoted by some of the WPF team at Microsoft.  I still think I‘d rather stick with Supervising Controller in most cases, but I‘m thrilled that people in MS itself are talking about this at all. It‘s an old post, but I‘d readMichael Swanson‘s thoughts on Presentation Model before you run off and use the pattern.
Three Musketeers Retirement Notice
The silly Three Musketeers thematic interludes just require more creativity than I can summon on a regular basis.  Let‘s just say they stopped the evil Lady de Winter in her diabolical mission (even though she‘s usually the most interesting character in the movie adaptations.  Seriously, who are you going to root for, Chris O‘Donnell or Rebecca De Mornay/Faye Dunnaway?  That‘s what I thought;) and delivered their very complex WinForms application on time with minimal fuss with a healthy infrastructure of automated testing.  And for the hard core Dumas fans, let‘s just forget about how badly things end in the Man in the Iron Mask because it still depresses me in a way that has only been topped by "they killed Wash!."
Where Next?
I‘ve got totally up the poll on this one, but for the sake of narrative continuity I‘m going to wrap up Model View Presenter with some quick and easy to write posts on View/Presenter communication and dividing roles.  After that, I‘m not sure yet, but the response has been so positive that I‘ll definitely keep going for a while.  I will finish this by no later than mid July.  I‘m shooting for 2-3 posts a week.

Build your own CAB Part #6 - View to Presenter Communication
If you‘re reading this post and wondering about 1-5, you might give the previous posts a perusal first.  This post (hopefully) builds on the previous posts in this series.
Build your own CAB Table of Contents
PreambleThe Humble Dialog BoxSupervising ControllerPassive ViewPresentation Model
View to Presenter Communication
Alright, I‘ve purposely hid the View to Presenter communication in my previous posts on Supervising Controller and Passive View because I thought that subject was worthy of its own post.  As I see it, there are 2 1/2 basic ways to communicate screen events back to the Presenter.
Expose events off of the IView interface. Jeffrey Palermo has told me before that he will do something very similar, but attaches delegates through setter properties instead.  I‘m calling that technique the "1/2" because it feels very similar to me to using events. Let the View have a reference to the actual Presenter and just call methods on the Presenter inside of screen events.
Just taking a straw poll of the blog posts out there about this topic, the majority of the world seems to favor events.  Just to be contrary, I very strongly prefer direct communication and it‘s time for that approach to get some love .
Doing it with Events
Making the View to Presenter communication work through events has the indisputable advantage of maximizing loose coupling.  The View doesn‘t even need to know that there‘s anything out there listening.  It‘s just shouting in the dark hoping someone will answer with help.  There‘s no need to pass around instances of the Presenter, so wiring MVP triads together is a little bit simpler.  Let‘s take a look.  The first step is to define the proper events on the View interface.  Here‘s an example from the Shipping Screen first described in theSupervising Controller post.
public delegate void VoidHandler();
public interface IShippingScreen
{
event VoidHandler ShippingOptionChanged;
string ShippingOption { get;}
}
The ShippingOptionChanged event is the interesting thing here.  When this event fires, the Presenter needs to recalculate the cost of the selected shipment and decide whether or not other shipment options for purchasing insurance or requiring a signature are still valid.  The actual View implementation is to simply relay the screen event with no interpretation:
public ShippingScreen()
{
InitializeComponent();
shippingOptionField.SelectedIndexChanged += new EventHandler(shippingOptionField_SelectedIndexChanged);
}
void shippingOptionField_SelectedIndexChanged(object sender, EventArgs e)
{
if (ShippingOptionChanged != null)
{
ShippingOptionChanged();
}
}
Now, on the Presenter side we have to register the event handler.  Since the event has a no argument signature, all we have to do is basically tell the screen which method on the Presenter to call.  No ugly anonymous delegates or ugly new SomethingDelegate(blah, blah) syntax.
public class ShippingPresenter
{
private readonly IShippingScreen _screen;
public ShippingPresenter(IShippingScreen screen)
{
_screen = screen;
// Attach to the event in the constructor
_screen.ShippingOptionChanged += this.ShippingOptionChanged;
}
public void ShippingOptionChanged()
{
// fetch the state the Presenter needs inside this operation
// from the Vjiew
string option = _screen.ShippingOption;
// do whatever it is that you do to respond to this
// event
}
}
And yes, I would definitely make the event handler methods public.  I think you should do at least one unit test to verify that you‘re wired to the correct event handler on the View interface, but otherwise I think you‘ll find it much more convenient to test the ShippingOptionChanged() method by calling straight into the ShippingOptionChanged() method.  I know the semantics of the unit test are simpler when you do it that way.
Assuming that you are going to unit test by simulating the event being raised, your unit test for the functionality above will look something like this (assuming that you use RhinoMocks anyway):
[Test]
public void HandleTheShippingOptionChangedEvent()
{
MockRepository mocks = new MockRepository();
IShippingScreen screen = mocks.CreateMock();
// Keep a reference to the IEventRaiser for ShippingOptionChanged
screen.ShippingOptionChanged += null;
IEventRaiser eventRaiser = LastCall.IgnoreArguments().GetEventRaiser();
// other expectations here for the Presenter interacting with both
// the backend and the View
mocks.ReplayAll();
// Raise the event
ShippingPresenter presenter = new ShippingPresenter(screen);
eventRaiser.Raise();
// Check the interactions
mocks.VerifyAll();
}
The thing to note is how we grab onto the event with RhinoMocks to simulate the event.  In a normal test harness I usually build the presenter under test and all of the mock objects in the SetUp() method.  That requires a little bit of knowledge about RhinoMocks to keep the tests running correctly.  Check out the links at the bottom to Phil Haack and Jean-Paul for more information on how to do this.
Direct Communication
Why do I prefer direct communication?  Two reasons.
"CTRL-B" and "CTRL-ALT-B."  If the this isn‘t ringing a bell, these are the ReSharper keyboard shortcuts you use inside one method to quickly navigate to another method (or class or interface or delegate, etc.).  I think it‘s easier to understand the codebase when there‘s a direct semantic link from View to Presenter and vice versa.  With direct communication I think the code is more intention revealing.  When I look at the View code I know more about what happens when a dropdown value changes.  With events there‘s more mechanical steps to figure out what‘s registered for the event. I think the mechanics for mocking events are awkward (I don‘t particularly have a better suggestion than what RhinoMocks does now).  Heck, I think events in general are awkward and I‘ve never liked them.  I would rather just treat my Presenter like anObserver of the View so I can make all of the event notification registration in a single line of code in the Presenter.
So the obvious downside is that now the View has to know about the Presenter, which spawns a new design question - who begat‘s who?  The majority of the time I say that it‘s a Presenter-centric world.  I create the Presenter first with the View coming in as a constructor argument.
public class ShippingScreenPresenter : IShippingScreenObserver
{
private readonly IShippingScreen _screen;
// The view is injected in through the constructor
public ShippingScreenPresenter(IShippingScreen screen)
{
_screen = screen;
}
// I suppose you could do this operation in the constructor instead, but
// it always feels so wrong to do much more than set fields in a constructor
public void Start()
{
// bootstrap the screen
_screen.AttachPresenter(this);
}
public void ShippingOptionChanged()
{
// do what you do so well
}
}
I usually have some sort of explicit call to a Start() method on my Presenter‘s to bootstrap the screen.  In this case, the very first operation in Start() is telling the View about the Presenter.  I know what you‘re thinking, this is going to tightly couple my View to the Presenter.  What if I want to use a different Presenter with the same View (it‘s not that uncommon)?  What if I want to test the View itself?  The easy answer is to treat the Presenter as an Observer of the View.  In my DevTeach talk I brought up the tight coupling issue and promptly did an "Extract Interface" refactoring with ReSharper to show how easy it was to decouple the View from the concrete Presenter.  No one was impressed.  The View only sees:
public interface IShippingScreenObserver
{
void ShippingOptionChanged();
// all other callback methods for screen events
}
The event handlers in the View itself get reduced to an immediate call to the Presenter (in bold).
public partial class ShippingScreen : Form, IShippingScreen
{
private IShippingScreenObserver _presenter;
public ShippingScreen()
{
InitializeComponent();
shippingOptionField.SelectedIndexChanged += new EventHandler(shippingOptionField_SelectedIndexChanged);
}
void shippingOptionField_SelectedIndexChanged(object sender, EventArgs e)
{
_presenter.ShippingOptionChanged();
}
public void AttachPresenter(IShippingScreenObserver presenter)
{
_presenter = presenter;
}
}
In the section on MicroController, I‘ll show how my project is creating the screen behavior for calls to the Presenter.
Best Practices in either case
The single best advice I think I could give is to make the communication as simple as possible.  As much as possible, make the callbacks and event handlers to the Presenter take in zero arguments.  Make the Presenter go back to the View and/or the Model to get current state.  On one had it makes the View simpler by eliminating code from the marginally testable View, on the other hand it decouples the View from needing to "Know" what the Presenter needs for its behavior determinations.  The exception cases would be for things like double clicking a single line inside of a grid to launch a new screen.  In that case I think the simplest thing to do is to send over just enough information in the handler for the Presenter to know which data member was the subject of the event.
The other advice I‘ll give is to make the method names for event handling on the Presenter be as descriptive as possible.  Ideally, you should be able to almost entirely comprehend the behavior of a screen from looking at the Presenter alone.
I‘ll talk about integration testing in later posts in this series.
Other Viewpoints
I‘m fully aware that I‘m almost a deviant by preferring direct calls from the View to the Presenter.  Here‘s the other side:
This very topic came up recently on Ayende‘s blogPhil Haack likes eventsJean-Paul has a nice technique for handling RhinoMocks and events, but the call to VerifyAll() in the TearDown() method feels like cheating somehow to me.Jim Bolla likes the Observable View
In the end, just talk it over with the rest of your team and decide if you want to be a cool kid like me or a slave to Microsoft‘s obsession with ugly event handling syntax, not that I want to prejudice you in any way;)

Build your own Cab - Answering some questions
First, go catch up on what‘s come before:
PreambleThe Humble Dialog BoxSupervising ControllerPassive ViewPresentation ModelView to Presenter Communication
I received some questions today that I thought were probably best addressed in a separate post.  If I‘ve confused one person, it‘s likely I‘ve confused many.  Here we go...
First Question
"So does the presenter provide the data from the model to the view, or does the view also have a reference to the model?  Or does it depend on which of the patterns from earlier in the series that you pick?"
Short answer:  Yes, sometimes, and it depends.
Long answer:  By and large I believe in the primacy of the Presenter, meaning that things start with the Presenter telling the View what to do rather than the other way around.  More specifically the Presenter "knows" about the Model first and then populates the View with the data in the Model.  Whether or not the Presenter fetches the Model, or is handed the Model, or creates the Model is a subject I‘m going to put off until the posts on creating the ApplicationShell and screen coordination.  Back to the original question, how the View gets the data depends on the pattern used for the screen.
Autonomous View -- There is no separate Presenter or Controller.  The View either creates the Model from scratch or gets the Model from another class Supervising Controller -- The Presenter/Controller is responsible for getting the Model first and setting up the View with all of the data it needs, including the Model.  With Supervising Controller we‘re still content to let the View know how to display the various properties of the Model through data binding or another mechanism.  In this pattern the View definitely has a reference to the Model and is largely responsible for synchronizing screen state with the Model directly. Passive View -- In this case the View has no reference whatsoever to the Model.  The Presenter synchronizes the screen state with the Model (and vice versa) by explicitly mapping properties of the Model to public properties of the View which in turn set screen state.  What you‘ll see in the View is a lot of getter and setter methods that delegate to screen elements like this:  get {return nameTextbox.Text;} and set {nameTextbox.Text = value;}. Presentation Model -- In this case the Presenter *is* the Model.  The View binds directly to the Presentation Model just like it would in the Supervising Controller
Second Question
"I‘m still wrapping my head around the Presenter.  Is it tightly coupled to the view?  For instance if I have some code that says turn these fields blue when the user does x, does that code live in the presenter or the view?"
That‘s a really good question because it skirts on some potentially treacherous ground.  How much should the Presenter know about the View?  How much should the View know about the Presenter?  Can I swap out the View?  If you read the scenario described above I‘d say that you have two distinct responsibilities:
Based on a certain user action, deciding that a visual indication should change on the screen (turning the fields blue) Making the visual indication on the screen
It‘s very often advantageous to separate out the responsibility for deciding to take an action from the responsibility of carrying out the action.  You‘ll see this time and time again in Object Oriented Programming, especially if you employ Test Driven Development.  Turning the fields blue is definitely a View responsibility to me.  This code in the Presenter _view.ColorOfFooField = ‘blue‘ feels very wrong to me.  I‘d rather the Presenter do this:  _view.IndicateFooIsSomeCondition().  The Presenter is supposed to be about behavior, and the second choice is much more semantically meaningful to me in terms of behavior.  The View is responsible for presentation and should get to decide how some sort of screen indication is made.
To summarize I guess I‘d say that the Presenter really shouldn‘t know the intimate details of the presentation, including color.  I think calls to EnableFoo() or DisableFoo() are generally correct because that is screen behavior that‘s generally determined by business rules and screen logic.  Ideally the Presenter should not be so tightly coupled to the View that you could not swap in a completely different View class (going from WinForms to WebForms may be too much to ask though).
Just to confuse the matter, I use the term "Embedded Controller" to refer to "user interface widget-aware" classes that can help a View do some of the presentation work.  For example, if I decide I want to make some sort of common screen indication (like turning a field that has invalid data or changed data blue) a common way across the system I might create an Embedded Controller that‘s reused across screens.  I call it an Embedded Controller because it‘s completely contained within a View as just a part of the View‘s machinery.  The most immediate example I can recall is a "GridHelper" class to help bootstrap the standard "sort, page, query, filter" functionality that‘s similar across screens.
My Question
"How does Acropolis effect this?"
I have no idea yet, but I‘ve heard it‘s supposed to be pretty cool.  I would have an idea, but I missed the Acropolis session at the MVP Summit because Bellware sent me on a wild goose chase to the wrong building.
Clear as mud?  You know, as many topics have come up from this series, I think this would be a good idea for a book...              ...written by someone else.