CodeBetter.Com
CodeBetter.Com
RSS 2.0 via Feedburner
           Do you Twitter? Follow us @CodeBetter

Jeremy D. Miller -- The Shade Tree Developer

Under the hood and working with .Net, TDD, Software Design, and Agile Stuff

October 2007 - Posts

  • Development Trivial Pursuit: The difference between MVC and the different flavors of MVP

    You can happily go your entire career without knowing the textbook definitions of either pattern and churn out working software.  On the off chance that you're training for some sort of Coding Trivial Pursuit, here's my shot at explaining the difference.

    My new teamate and I had a discussion a couple weeks back on design patterns for user interface and he was using the terms MVP and MVC interchangeably.  Being the obnoxious pedant that I am, I told him that they weren't quite the same thing, but had to run to the train before I could explain.  Later, the discussion became a little more serious as we got into the details of our system.  My new coworker is familiar with the Passive View approach to Model View Presenter (MVP)  and was trying to frame the implementation of his new feature in those terms.  For a variety of reasons I've followed a Supervising Controller pattern in our WinForms client.  Once I explained the difference and spent a little time on the rationale behind my design decisions he was able to work inside the architectural conventions and make some beneficial suggestions.  In this case, understanding the differences between two outwardly similar flavors of the Model View Presenter design pattern turned out to be important.

    While all variants of both MVC and MVP are an attempt to separate the various responsibilities of a screen into cohesive classes, they differ in the details.  In a classic Model View Controller architecture, both the View and Controller have a reference to the Model.  Both View and Controller "observe" the Model and directly manipulate the properties of the Model.  There is typically little or no direct communication between the View and Controller.

    In a Model View Presenter architecture the Presenter (basically the Controller) communicates directly with the View and tells the View what to do.  The Presenter is also listening directly to events from the View and takes action when an event is raised from the View. 

    If you're peeking ahead to Acropolis, you'll see yet a third way to split up responsibilities in a screen that's neither MVC or MVP.  As far as I can tell, Acropolis is pushing a Presentation Model approach that effectively merges the "Model" and "Presenter" into a single Presentation Model (or hides the Model inside the Presenter).  In this case, the View is bound directly to the Presentation Model.  Whereas the Model in MVC/MVP is typically ignorant of the screen, the Presentation Model is fully part of the screen behavior and can expose screen specific properties like "TheSuchAndSuchIsEnabled" or "ButtonsAreVisible."  The Presentation Model classes might completely wrap what would be the Model in an MVC/MVP architecture.  Microsoft's name for this pattern is Model-View-ViewModel, which might be a more apt description anyway. 

     

    Web vs. Thick Clients

    The relationship between the View and Presenter in MVP is continuous and the state is generally in the View and/or Model.  Because of this, MVP is most appropriately applied to stateful screens like WinForms or Swing clients.  I've used both flavors of MVP with WinForms and been pleased with the results.  While there's absolutely nothing in WinForms to encourage you to go down any kind of MVC or MVP approach, there's not much stopping you from using MVP.  I don't see any reason why you couldn't do classical MVC with WinForms, but MVP seems simpler to me.

    Web clients are a completely different story.  You can do MVP with WebForms like I wrote about way back when, but I've found it to be no better than an acceptable compromise.  On the other hand, you've no doubt seen a tremendous amount of buzz over Microsoft's new MVC framework for web development.  As applied to web development, MVC means a linear cycle of:

    1. Get the request in some sort of Front Controller
    2. Select the Controller and method to call
    3. If required, handle the requested transaction
    4. Build the Model structure of the data to be displayed
    5. Pass off the Model to the View to render into HTML

    In this case the Controller simply builds the Model and passes it off to the View for rendering.  No stateful interplay between the View and Controller, just a "hey, here's the Model, see you later" from the Controller to the View.

     

     

    If my explanations were worth anything, you should now be perfectly confident in your ability to get that last pie piece in the development version of Trivial Pursuit.

  • Be not afraid of the Visitor, the big, bad Composite, or their little friend Double Dispatch

    Last week or so there was a thread on the altnetconf message board that about a usage of the Visitor pattern for validating a hierarchy of objects.  At work I'm using the Visitor pattern with some frequency in my financial projects to deal with heterogeneous collections of financial elements.  Over and over again I'm seeing the Composite and Visitor patterns come up as good solutions to a certain range of problems, but these patterns are often a source of almost superstitious fear to those developers who aren't familiar with them.  From past experience I know that developers don't necessarily grok these patterns at the first exposure.  I avoided the Visitor for a long time because it's just plain weird looking.  I changed my mind only after having some positive experiences with the pattern. 

    I've had a post on these patterns backlogged forever, so now seems like as good of time as any to try to help introduce these important patterns.  All of the example code from this post is part of my StoryTeller OSS project and can be perused to your heart's content from the Subversion repository on Tigris. 

    Specifically, I'm going to talk about design patterns that are useful for processing heterogeneous lists and object hierarchies without resorting to an uncontrolled proliferation of "if/then" branches:

    1. The almost forgotten art of Double Dispatch
    2. Fear not the Visitor
    3. The Big, Bad Composite Pattern

    I struggled quite a bit with the ordering of topics in this post because the patterns seem to be so closely interrelated in my mind.  Double Dispatch stands alone, but the reason for doing it is largely to make the Visitor implementation work.  I've used a Visitor pattern frequently at work the past couple months without a Composite, but most of the time the Visitor and Composite seem to be found together.

    Before I get started...

    <BoilerPlateDesignPatternDisclaimer>

    Design Patterns are a very useful are of study for serious software designers.  Design Patterns are an important form of common language between developers and a way to catalogue and reuse design wisdom from the ancients.  Design Patterns can be a huge shortcut for designing applications or services.  Overusing Design Patterns is bad.  Using Design Patterns out of their proper context is usually bad.  Committing to a  Design Pattern too quickly can often be bad.  Using Design Patterns at the right times can reduce the amount of ugly, bugridden "if/then" logic in code and make the code easier to test, change, and read.  Don't just memorize pattern names.  Climb up to the top of Bloom's Taxonomy

    </BoilerPlateDesignPatternDisclaimer>

    Now that that's out of the way...

    The Problem

    My Domain Model in StoryTeller is largely made up of a series of classes that inherit from a common ILeaf interface and represent the concepts in Fit-style testing.

    • Suite - a group of tests and/or child suites
    • Test - contains a mix of Comment's and Tables, could contain a reference to a Fragment
    • Comment
    • Table - The actual test.  A Table contains rows which contains cells. 
    • Fragment - a reusable piece of test logic.  Think SetUp or TearDown.  Can contain Comments and/or Tables
    • Include - simply a reference to a Fragment
    • SystemUnderTest - the configuration and list of Suites for an entire system.  Effectively the equivalent to a "project" for StoryTeller.

    In hierarchical form a SystemUnderTest and its children may look something like:

    1. SystemUnderTest:  "StoryTeller UI"
      1. Suite:  "Test Operations"
        1. Fragment:  "SetUp"
        2. Fragment:  "TearDown"
        3. Suite:  "Add Test"
          1. Test:  "Add Test Happy Path from Tree"
          2. Test:  "Strip illegal characters from Test name"
            1. Table
            2. Comment
            3. Include/Fragment
            4. Table
            5. Table
        4. Suite:  "Delete Test"
      2. Suite:  "Tagging"
      3. Suite:  "Test Execution"

     

    Introducing the Composite and Visitor Patterns 

    From the original Gang of Four:

    Compose objects into tree structures to represent part-whole hierarchies. Composite lets clients treat individual objects and compositions of objects uniformly.

    A composite object is simply an object that is composed of other objects.  A SystemUnderTest object will contain one or more Suite objects.  A Suite class from StoryTeller will contain other Suites and Test objects in an n-deep hierarchy.  I have to do many different operations against an array or hierarchy of ILeaf objects.  For example, starting from any particular ILeaf object I need to:

    1. Save each ILeaf, but all the different types of ILeaf classes are persisted a little bit differently
    2. When constructing the TreeView in the UI I need to create a TreeNode for each ILeaf object in the hierarchy, but I use a different subclass of TreeNode for each specific type of ILeaf
    3. Render each ILeaf into an HTML representation, but each ILeaf is rendered somewhat differently
    4. Find all the Tests that match a given criteria starting from anywhere in the hierarchy
    5. Execute all the Tests at any level of the hierarchy
    6. Find any particular ILeaf by the path or a unique identification
    7. Later on I'm planning on adding syntax checking and possibly refactoring that will have to scan the entire hierarchy

    All of the different types of "node" have a consistent set of operations, so it makes sense to create a common interface for all of these "node" classes.  Going farther, doing an operation on any given node usually means that I also need to perform that same operation on all the children of that node and the descendents.  This is where the Composite Pattern comes into play.  Implementing the Composite Pattern means that I need to treat the leaf and branch nodes of the hierarchy in a common manner. 

    To implement the Composite Pattern I've created the ILeaf interface below:

        public interface ILeaf
        {
            IEnumerable<ILeaf> ChildLeaves { get; }
            ILeaf[] Children { get; }
            void AcceptVisitor(IVisitor visitor);
        }

    In StoryTeller I've chosen to implement almost all of the hierarchical operations in Visitor pattern classes, but as we'll see in a later section the Visitor approach wouldn't work without the Composite pattern implemented by the common ILeaf interface.  If I hadn't decided to keep almost all infrastructure concerns out of the ILeaf nodes, I might have added an "Execute()" method on the ILeaf interface.  If you had called Test.Execute() it would simply execute itself.  If you called Suite.Execute() it would call Execute() on all of its children Suites and all of its Tests so that every Test that descended from that Suite would be executed.

     

    Other Examples for the Composite Pattern

    The average software developer probably uses the Composite pattern every single day in existing libraries and API's:

    1. The DHTML DOM in web browsers
    2. The Control hierarchy in WinForms.  Many of the methods you call on a Control will propagate down into its children and its children's children.
    3. The FileSystem is composed of an n-deep hierarchy of folders and files.  Deleting a folder also deletes all of its subfolders and all of the files that it contains.
    4. The Xml DOM is the canonical example.  No matter where it is in the hierarchy, you basically treat each XmlNode as an XmlNode.
    5. In manufacturing systems an assembly of parts is often treated as just another part.  I used to work for a computer manufacturer in Texas.  With the advent of blade servers a server could be said to be composed of an array of blade servers which all had their own set of parts.  If the manufacturing system had been built along OOP lines with the Composite pattern describing the constituent parts, sliding in support for a rack server composed of blade servers wouldn't have had to hurt too much.  Alas, the manufacturing system was still written in spaghetti code COBOL and out came the "if/then" duct tape.

    I can't say that I create new Composite pattern implementations from scratch on a regular basis, but it pops up often enough to warrant an inclusion in your design toolbox.  I've used the Composite for:

    1. The StoryTeller domain model of Suites and Tests
    2. In StructureMap, I create an in memory hierarchy of the configuration model for the diagnostics.  One instance has child instances which may have child instances which may have constructor arguments.
    3. In an insurance application we had a model of regions, customers, and policies that naturally fit a Composite model.  I got a lot of push back from other developers on this project that weren't familiar with the Composite pattern because it seemed too "weird."  I still think it was the simplest way to pull off the model with our requirements, but the unfamiliarity with the pattern was a real problem.  I'm writing this post in no small part to have a published explanation for the Composite and Visitor for the next time I'm in this situation.
    4. Any number of custom filter "trees."  I'd like to have a quarter for every time I've written an IFilter interface of some kind.  Any time you do, there's almost inevitably a "NotFilter" and "OrFilter" and "AndFilter" that combine other IFilters to create more complex query behavior. 

     

     

    Double Dispatch

    Before I introduce the Visitor pattern, I need to first demonstrate the ancient technique of Double Dispatch.  To illustrate the concept, let's take a look at the Double Dispatch you've used your entire .Net career to do Xml serialization.  Here's a sample snippet of code to Xml serialize an object to a file.

     

            public void PersistToFile<T>(T target, string filename)
            {
                XmlSerializer serializer = new XmlSerializer(typeof (T));
     
                using (FileStream stream = new FileStream(filename, FileMode.Create, FileAccess.Write))
                {
                    serializer.Serialize(stream, target);
                }
            }

    We create an XmlSerializer object for the Type of object that we're serializing.  Then we create a FileStream object that we want the data written to, eventually landing in an Xml file.  The last thing we do is to pass the FileStream object into the XmlSerializer.  As the XmlSerializer works, it figures out the content to write and tells the FileStream to write this content.  If the FileStream and XmlSerializer were people, their conversation might be summed up as:

    FileStream:  "Here I am, now you tell me what to do for you."

    XmlSerializer:  "Write <SomeClass>.  Write <SomeProperty>SomeValue</SomeProperty>..."

    So the two classes aren't great conversationalists, but the technique is a powerful slayer of if/then logic.  Think about this for a minute.  XmlSerializer, the binary serialization, and the newer JSON serializer's all have very different logic to determine the exact bytes or characters that represent an object, but the bytes produced are basically stored in the same way.  When you serialize an object, however, the Stream object doesn't need to care what type of serialization is taking place.  The specific serializer will tell the Stream what to write. 

    Here's a sample usage of Double Dispatch from StoryTeller.  At various times in the code I need to take an ILeaf object and write out the HTML representation of it.  Let's say I'm writing out a single Test to use as the HTML input to the FitnesseDotNet test engine.  Any given Test will be composed of a mix of Comments, Tables, and Fragments.  All three of these things will be rendered to HTML in a different way.  In this case there's a finite number of tasks that need to take place to render a Test into HTML.  I came up with a simple interface for all of these little HTML writing tasks:

     

        public interface IHTMLBuilder
        {
            void StartTable();
            void StartTable(Type type);
     
            void AddComment(string commentText);
     
            void AddRow();
            void AddRow(params string[] contents);
            void AddRow(string delimitedList);
            void AddCell(string contents, int width);
     
            string GetHTML();
     
            void WriteTitle(string title);
            void WriteTag(string tag);
            void AddStyle(string style);
            void StartInclude(string path);
            void EndInclude();
     
            void WriteBigTitle(string title);
            void AddDivider();
     
            void WriteStatus(Status status);
        }

    Next, we've got the issue of where to put the specific logic for rendering each type of ILeaf.  HTML rendering in StoryTeller is so intrinsic that I decided to embed the HTML rendering into each ILeaf type that needs to be rendered.  Let Table and Row and Column know how to render themselves.  That decision led to the creation of one more interface shown below:

        public interface IHTMLFragment
        {
            void WriteHTML(IHTMLBuilder htmlBuilder);
        }

    To render a Comment object I simply pass an IHTMLBuilder into the WriteHTML(IHTMLBuilder) method and let the Comment class tell the IHTMLBuilder what to do.

     

            public void WriteHTML(IHTMLBuilder builder)
            {
                builder.AddComment(_contents);
            }

    The Table class is a little bit more complicated, but it's still the same concept.  For the sake of completeness, I'm also showing the code in Row and Cell.

     

            public void WriteHTML(IHTMLBuilder builder)
            {
                CalculateCellWidths();
                builder.StartTable();
                foreach (Row row in _rows)
                {
                    row.WriteHTML(builder);
                }
            }
     
            // Row.WriteHTML(IHTMLBuilder builder)
            public void WriteHTML(IHTMLBuilder builder)
            {
                builder.AddRow();
                foreach (Cell cell in _cells)
                {
                    cell.WriteHTML(builder);
                }
            }
     
            // Cell.WriteHTML(IHTMLBuilder builder)
            public void WriteHTML(IHTMLBuilder htmlBuilder)
            {
                htmlBuilder.AddCell(_contents, this.Width);
            }

    In my first pass at this code the Test class could only contain Comments or Tables.  In a later pass I added the ability to "include" fragments of tests into other tests.  No worries though, I simply have yet another class called Include that also implements IHTMLFragment (oops, I just found a bug related to this in StoryTeller while writing this).  When the Test is being rendered the HTMLWriter just iterates over all of the ILeaf children.

    Okay, so each thing knows how to tell an IHTMLBuilder how to persist itself, but how does an IHTMLBuilder get around to each Table, Comment, and Fragment?  That's where the other patterns come into play.  We've used the Composite pattern already to standardize the navigation from an ILeaf to its children all the way down.  Now we need to introduce the Visitor as a way of creating a logical action that starts working from any given ILeaf node.

     

    Fear not the Visitor

    From the Computer Science department of my alma mater:

    The purpose of the Visitor Pattern is to encapsulate an operation that you want to perform on the elements of a data structure. In this way, you can change the operation being performed on a structure without the need of changing the classes of the elements that you are operating on. Using a Visitor pattern allows you to decouple the classes for the data structure and the algorithms used upon them.

    As I said before, I need to perform a series of operations against all or part of an ILeaf hierarchy in StoryTeller.  Some of these operations pertain to infrastructure or user interface concerns.  I don't want these concerns embedded in my domain model, so its advantageous to implement these operations in other classes.  Very often these operations will involve a mix of the different types of ILeaf objects.  If I were to use straight up procedural programming, I'd be constantly writing the same set of if/then/switch statements all over the place every time I need new operations against a mix bag of ILeaf objects.

    The Composite Pattern gives us a standard pattern for navigating the data structure.  The next step is to be able to differentiate the proper action based on the type of ILeaf object that we're processing.  Once again we're going to turn to Double Dispatch to help us out.  We first define a new interface called IVisitor that exposes specific methods for processing each specific kind of ILeaf.

     

        public interface IVisitor
        {
            void ProcessTest(Test test);
            void ProcessTable(Table table);
            void ProcessComment(Comment comment);
            void ProcessSuite(Suite suite);
            void ProcessInclude(Include include);
            void ProcessFragment(Fragment fragment);
        }

    As we saw earlier, each ILeaf exposes methods to support both the Composite structure and a single method called AcceptVisitor(ILeaf) that enables the Visitor pattern.

     

        public interface ILeaf
        {
            IEnumerable<ILeaf> ChildLeaves { get; }
            ILeaf[] Children { get; }
            void AcceptVisitor(IVisitor visitor);
        }

    When the AcceptVisitor(ILeaf) method is called on an ILeaf, the ILeaf simply turns right around and calls the proper method on the IVisitor and passes itself in as the argument.  Here's the implementation of AcceptVisitor() for the Test class.

            public override void AcceptVisitor(IVisitor visitor)
            {
                visitor.ProcessTest(this);
            }

    All the Test has done is simply told the incoming IVisitor that "I'm a Test, so do whatever it is you do with a Test." 

    So why is this advantageous over simply doing a switch statement on the type?  I'd say it's advantageous because:

    1. We've eliminated the need to write the same switch statement over and over again as new operations are added to the system
    2. The code to split processing by the type of ILeaf is cleaner in my opinion because we've removed "noise" code by letting the Visitor pattern handle the conditional logic
    3. It provides a template for new operations to follow
    4. It provides an obvious entry point for unit testing against any particular kind of node in the hierarchy.  A couple years ago I hit a point in StructureMap where the diagnostic code was an abominable mess.  Unit testing was hard because there was a tight coupling between configuration code and the diagnostics.  I largely cured the problem by refactoring the diagnostics to a Visitor pattern to the point where it was easy to skip the configuration setup in unit tests to go right to the smaller scenario that I wanted to unit test.  Using the Visitor pattern ended up making the diagnostic code far easier to work with.

     

    Creating TreeNodes with the Visitor

    The StoryTeller UI has a TreeView on the left that shows a TreeNode for each ILeaf in the open SystemUnderTest.

    I use a specific subclass of the WinForms TreeNode class for each type of ILeaf in order to expose specific actions and screen navigation.  When I'm constructing the TreeNode hierarchy I logically need to iterate over each ILeaf's children and create the proper type of TreeNode for each ILeaf child.  This construction of the TreeView really became very simple by using the IVisitor interface that already existed by this time.  All of my TreeNode's extend the abstract LeafNode class shown in elided form below:

     

        public abstract class LeafNode<T> : TreeNode, ILeafNode, IVisitor where T : ILeaf
        {
            private readonly T _screenSubject;
     
            protected LeafNode(T subject)
            {
                _screenSubject = subject;
                ...
                RefreshNodes();
            }
     
            public void RefreshNodes()
            {
                Nodes.Clear();
                ...
                foreach (ILeaf child in ((ILeaf) _screenSubject).ChildLeaves)
                {
                    child.AcceptVisitor(this);
                }
            }
     
            public virtual void ProcessTest(Test test)
            {
                TestNode node = new TestNode(test);
                Nodes.Add(node);
            }
     
            public virtual void ProcessSuite(Suite suite)
            {
                SuiteNode node = new SuiteNode(suite);
                Nodes.Add(node);
            }
     

    When LeafNode's constructor is called it takes in an ILeaf as its "subject."  The last step in its constructor is to call the RefreshNodes() method to create all of its child TreeNodes.  If this were the SuiteNode, the steps in code would be:

    1. Take in a Suite object as an argument to the constructor
    2. In the RefreshNodes() method, iterate over each ILeaf child in the Suite (_screenSubject above)
    3. For each ILeaf child the SuiteNode will pass itself into the ILeaf.AcceptVisitor() method
    4. If the ILeaf child is a Test, the Test will immediately call the ProcessTest(Test) method on the SuiteNode object...
    5. ...which causes a new TestNode to be created for that Test and added to the Nodes collection of the SuiteNode
    6. If the ILeaf child is another Suite, that child Suite will immediately call the ProcessSuite(Suite) method on the SuiteNode object...
    7. ...which causes a new SuiteNode to be created for that child Suite -- which will in turn follow the same process to build its children before...
    8. ...the new child SuiteNode is added to the Nodes collection of the original SuiteNode...

    It may not seem this way at first glance, but this strategy made the population of the TreeView very simple to implement and unit test.

     

    Combining the Visitor and Composite

    The StoryTeller version of the Visitor is relatively simple and I think fairly representative.  I use a simple abstract class called Visitor as a common superclass.  That class is shown below:

     

        public abstract class Visitor : IVisitor
        {
            #region IVisitor Members
     
            public abstract void ProcessTest(Test test);
            public abstract void ProcessTable(Table table);
            public abstract void ProcessComment(Comment comment);
            public abstract void ProcessSuite(Suite suite);
     
            public virtual void ProcessInclude(Include include){}
            public virtual void ProcessFragment(Fragment fragment){}
     
            #endregion
     
    
    
            public void VisitLeaf(ILeaf leaf)
            {
                // Hook method before processing an ILeaf
                startLeaf(leaf);
     
                // Another hook to filter ILeaf's before processing
                if (isInterested(leaf))
                {
                    leaf.AcceptVisitor(this);
                }
     
                // Now, visit each child of the original ILeaf
                foreach (ILeaf child in leaf.ChildLeaves)
                {
                    VisitLeaf(child);
                }
     
                // Hook method after processing an ILeaf and all
                // of its children
                endLeaf(leaf);
            }
     
            protected virtual void startLeaf(ILeaf leaf){}
     
            protected virtual void endLeaf(ILeaf leaf){}
     
            protected virtual bool isInterested(ILeaf leaf)
            {
                return true;
            }
        }

    The mechanics for navigating the ILeaf hierarchy is completely implemented in the VisitLeaf(ILeaf) method.  In its simplest form a Visitor implementation would simply call AcceptVisitor(this) on the leaf argument, then iterate over all of leaf's children to visit each of them in turn.

    When doing a Visitor implementation I've often found it to be advantageous to provide "hook" methods before and/or after the processing of each node.  These hooks are usually for bookkeeping or times when you can really perform the operation through the common interface of the nodes.  One of the ways I use this in StoryTeller is in the HTML rendering of an ILeaf hierarchy.  Several of the ILeaf types also implement the IHTMLFragment interface I introduced earlier to write themselves out in HTML.  HTML rendering is done in a subclass of Visitor called HTMLWriter.  In HTMLWriter I override the startLeaf() method to write out HTML for each ILeaf in a generic manner:

            protected override void startLeaf(ILeaf leaf)
            {
                IHTMLFragment fragment = leaf as IHTMLFragment;
                if (fragment != null)
                {
                    fragment.WriteHTML(_builder);
                }
            }

     

    Usually, however, the meat of the Visitor operation is happening in the ProcessXXXXXXXX() methods.  In the HTMLWriter I have specific logic for handling a Suite or a Test in the IVisitor methods shown below:

            private IHTMLBuilder _builder;
            private ILeaf _leaf;
     
            public HTMLWriter(ILeaf leaf, IHTMLBuilder builder)
            {
                _leaf = leaf;
                _builder = builder;
            }
     
            public string GetHTML(bool withStyle)
            {
                addStyle(withStyle);
     
                VisitLeaf(_leaf);
                return _builder.GetHTML();
            }
     
            private void include(Fragment fragment)
            {
                ...
            }
     
            protected override void startLeaf(ILeaf leaf)
            {
                IHTMLFragment fragment = leaf as IHTMLFragment;
                if (fragment != null)
                {
                    fragment.WriteHTML(_builder);
                }
            }
     
            public override void ProcessTest(Test test)
            {
                _builder.WriteTitle(test.Name);
                _builder.WriteStatus(test.Status);
                foreach (string tag in test.Tags)
                {
                    _builder.WriteTag(tag);
                }
            }
     
            ...
      
            public override void ProcessSuite(Suite suite)
            {
                _builder.WriteBigTitle("Suite " + suite.Name);
                foreach (string tag in suite.Tags)
                {
                    _builder.WriteTag(tag);
                }
                _builder.AddDivider();
            }
     

    By making HTMLWriter a Visitor, I can take any given ILeaf and write it and all of its children into HTML.  Because I can start the HTML rendering from any point in the hierarchy I've been able to reuse the same class for:

    1. Exporting an entire Suite of tests to HTML
    2. Exporting all of the tests in a SystemUnderTest to HTML
    3. Writing out a single Test prior to execution
    4. Rendering a Fragment into an HTML preview view

    When I've needed to alter the way ILeaf objects are rendered to HTML it's been easy to find the write code to change.  I simply have to find the appropriate ProcessXXXXXXX() method on HTMLWriter and make the changes there without having to be concerned about the code for rendering any other kind of ILeaf.

     

    How does the Visitor Get Around?

    I'm aware of three different ways to handle the navigation of the Visitor through a list or hierarchy.

    1. The Visitor itself is responsible for navigating the hierarchy.  This is the approach I've used in StoryTeller's ILeaf hierarchy.  Each ILeaf exposes a ChildLeaves property that standardizes the navigation from parent to children for all types of ILeaf.  In this case my Visitor classes don't really need to know that much about the internals of the hierarchy and I didn't feel that it created an unacceptable coupling.  I don't like this option if it means making the Visitor intimately aware of the internal structure of the hierarchy that it's visiting.
    2. Make each node in the hierarchy responsible for passing the Visitor down to its children.  I use this approach when I don't want to expose the internal structure of the hierarchy to the Visitor.  It's also a great way to make each node responsible for conditional propagation of the Visitor. 
    3. Use a separate class as an iterator to walk the hierarchy and "push" the Visitor to each node in the hierarchy.  I think this can simplify the Visitor classes by removing the need for inheritance relationships.  It also makes the navigation of the hierarchy easier to maintain and test by isolating the navigation from the Visitor actions.  The downside is potentially a little extra mechanical complexity in using the Visitor against a hierarchy because of the extra class.

     

    Yield is your Friend

    The new "yield" keyword is almost tailor made for creating Visitor/Composite pattern implementations.  With the yield keyword I can structure my hierarchy in any way that's appropriate and still make the enumeration of the children seem simple to the outside callers.  In my Suite class it's advantageous for me to keep the child Fragments, Tests, and child Suites in separate data structures.  However, when the ChildLeaves property is requested for a Suite I want to iterate through all three collections.  In .Net 1.1 I probably would have created some sort of temporary ArrayList or ILeaf[] array just to hold the returned value.  In .Net 2.0 I can use the "yield" keyword to eliminate the unnecessary shuttling of data in temporary lists like this:

     

            public override IEnumerable<ILeaf> ChildLeaves
            {
                get
                {
                    foreach (KeyValuePair<string, Suite> pair in _childSuites)
                    {
                        yield return pair.Value;
                    }
     
                    foreach (KeyValuePair<string, Test> test in _tests)
                    {
                        yield return test.Value;
                    }
     
                    foreach (KeyValuePair<string, Fragment> pair in _fragments)
                    {
                        yield return pair.Value;
                    }
                }
            }

     

    Yes, I know this is easier in Ruby!

    The Ruby Visitor from ObjectMentor.  Ruby guys love to use this example to poke fun at the compiler driven noise in static typed language like Java, C#, and VB.Net.

    Summary

    So was all of this worth it to me?  Looking back I'd say the answer is an emphatic yes.  I counted 20 implementations of the IVisitor interface in StoryTeller.  I've been able to add new operations across the hierarchy with relative ease.  I know I've got at least a couple more hierarchy operations yet to do in later phases and the Visitor/Composite pairing gives me a clean way to add these operations.

    If you have a need to process an object hierarchy and/or a mixed list of objects, the Visitor and Composite patterns can do a lot for you to control the complexity of dealing with the data structure.

    Other Reading

    I did quite a bit of reading in the course of writing this post.  In particular, I found these references helpful:

    If you peruse these links you might notice that not one single one of the links uses .Net or even mentions .Net.  Not really making a statement of any kind, just pointing that out.

  • How you're writing WinForms apps - The results

    Last time I asked the question "How are you building WinForms applications?" just to get a sense of how everyone else is doing things.  Here's my tabulation of results with some comments below.  I had to apply some interpretation here, so take the numbers with a grain of salt.  Besides, it's also a little bogus to tabulate because I'll use a combination of Passive View, Supervising Controller, and Presentation Model within the same application depending upon the screen.  Plenty of you said the same.

    1. Composite Application Block:  4
    2. Presentation Model or Model-View-ViewModel:  5
    3. Passive View (I'm including Presenter First in this bucket):  8
    4. Supervising Controller:  11 
    5. Legacy Code ported from VB6 that's not my Fault!:  6

    plus one vote for Wendy's View to Command wiring.

    Lots of folks doing Model centric validation.  I was pleasantly surprised by that, but shouldn't have been.

    Comments

    The decisions seem to be based on the logical things.  If you trust data binding or at least think it's a time saver you're more likely to choose Presentation Model or Supervising Controller.  If you're paranoid about test coverage, you pick Passive View. 

    If you ported from VB6 you're out of luck.  When I was coding VB6 I didn't have a clue about View/Controller separation, and I'd bet the mass majority of my peers were in the same predicament there.

     

    Next time, I'm going to try to compile a list of what everybody thought was hard and see if I can connect some links and patterns to some of it.  I was glad to see I wasn't the only person unhappy enough with Data Binding to go their own way.

  • What should the Patterns and Practices team be doing?

    Glenn Block is asking for community feedback on what we want the Patterns and Practices group at Microsoft to be.  The loudmouths on the altnetconf board have had our say, so now go and add yours.

  • How are you building WinForms applications? What's hard about it?

    Just an unscientific poll because I don't get to talk to too many other people building larger enterprise applications with WinForms.

    How are you structuring your WinForms application?  Passive View MVP?  Supervising Controller MVP?  Atomic Object's Presenter First MVP?  Presentation Model (Model-View-ViewModel)?  Using the CAB?  Lumping everything into the Form's because you don't see the need for MV*?  Something else?

    What are your challenges?  Automating tests against the UI?  Cross screen communication?  Cross screen state?  Dynamic Menus?  Division of responsibilities between the MVP triad pieces?  Validation?

     

    I'll gather up the results later.  At a minimum I'm writing up some stuff on testing through the UI itself.

     

  • Build your own CAB #15 - MicroControllers

    After a bit of a hiatus and a fair amount of pestering, I'm back and ready to continue the "Build you own CAB" series.  The point isn't really to go build a drop in replacement for the Composite Application Block (CAB), but rather to understand the design patterns you can use to build maintainable WinForms applications.  I'm hopeful that the material in this series will be useful for both users of the CAB and those who are rolling application specific architectures sans CAB.  The previous posts have been mostly written at the perspective of a single screen.  For this post I want to go down to the granular control level before coming back up to finish the series with content on coordinating multiple screens and composite applications.  My longer term goal is use the BYO CAB series as the kernel of a book on design patterns for fat clients and composite applications, so I'd love any kind of feedback no matter how negative.

     

    MicroControllers

    I introduced what I call the MicroController pattern in my last installment.  The basic idea is to use a small controller class to govern an atomic part of the screen, usually all the way down to the individual control or a small cluster of controls.  The assumption is that it'll be easy to reuse the very small controller classes across screens and also to test these little critters under an xUnit microscope.  I've found that it's often advantageous to then aggregate those MicroController's to create powerful behaviors.  I'm going to take this idea a little bit farther and show some usages of the MicroController pattern to create an alternative to Data Binding for screen synchronization.  When I first wrote about this idea in My Crackpot WinForms Idea, I said that I'd do a further writeup if the technique was successful.  I've used it long enough now to know that I'm happy with the results overall, and more importantly, I'd like some feedback on this approach before I think about using it again.  As I'll try to demonstrate in this post, I'm claiming the MicroController approach leads to improvements in productivity and testability.

     

    Background

    I'm going to refer to two different projects in this post.

    1. TradeCapture 1:  A project that I did late last year and early this year.  We used WinForms data binding and ran into major stumbling blocks with automated testing
    2. TradeCapture 2:  One of the projects I've been working on since April.  I'd used the MicroController strategy on previous projects, but this is the project where all the techniques shown here were developed and tested.  The design of TradeCapture 2 was heavily influenced by my interpretation of our struggles from TradeCapture 1.

    I'm using slightly obfuscated examples from TradeCapture 2. An early, but functional version of the MicroController strategy is in the StoryTeller codebase at http://storyteller.tigris.org/svn/storyteller/trunk/src/StoryTeller.DataBinding.  If you down load the entire code tree at http://storyteller.tigris.org/svn/storyteller/trunk you'll find a couple small screens that use the techniques from this article.  ReSharper "Find Usages" is your friend.

     

    What's the Problem?

    If you stop and think about it, there's a huge amount of repetitive tasks that you need to do at the individual control level.  Here's a partial list of the tedious chores that can easily fill up your day on a WinForms project: 

    • Bind controls to a property of the Model
    • Fill dropdown boxes with reference data fetched from some sort of backend
    • Use the ErrorProvider to display validation errors by control
    • Disable or hide controls based on user permissions
    • Capture change events off controls to trigger some other sort of behavior
    • Do "IsDirty" checks
    • Reset all the values back to the original state
    • Inside of an automated test, you need to be able to find a certain control and then manipulate it
    • Format data in screen elements.  In my project we need to make some textbox's accept numeric values in the form "1k" or "1m" to enter large numbers.  In other applications you may have other formatting and parsing rules repeated over controls.

    The designer time support in Visual Studio makes it easy to create these types of behavior from scratch.  That's great, but it leads to a lot of duplication, code noise, and difficulty in making behavioral changes across multiple screens harder.  In the last bullet point in my list above, I had to go back and accept "1b" as the value 1,000,000,000 in textbox's representing monetary amounts.  It wasn't any big deal because I only had one single method in a single MicroController class to modify.  But what if I'd created that behavior through implementing event handlers separately for each textbox?  That'd be a lot of code to duplicate and change.

     

    Screen Synchronization with MicroControllers

    For a variety of reasons I wanted more predictable screen synchronization than Data Binding provides.  Add in the drag (I'll talk about this at length in the next BYO CAB post) of Data Binding in automated testing scenarios and I was ready to try something different.  I ended up using a scheme that I'd previously applied to Javascript heavy DHTML clients.  I would create a MicroController class for each type of Control that knew how to bidirectionally synchronize data from the Model classes to the Controls.  The mechanics for each type of control (textbox, radio buttons, checkbox, listbox, etc.) are slightly different, but the goals and intentions are basically the same.  As an example, for every type of control I might want to:

    • Synchronize the value of a property on the Model with a Control on the screen
    • Apply changes from a Control value back to a property on the screen
    • Attach error messages to a Control by the name of the property the Control is bound to
    • Simulate a "Click" event
    • Register for changes in the Control's value
    • Reset the Control values back to the original property value of the Model class
    • Determine if the Control is "dirty"
    • Enable or disable Controls

    The key is to make each type of Control/MicroController look the same for basic operations.  I do this by making each MicroController implement the IScreenElement interface partially shown below:

     

        public interface IScreenElement
        {
            string LabelText { get; }
            string FieldName { get; }
            Label Label { get; set; }
            ErrorProvider Provider {set;}
            ...
            void Bind(object target);
            bool ApplyChanges();
            void SetError(string errorMesssage);
            void Reset();
            string GetError();
            void RegisterChangeHandler(VoidHandler handler);
            void Update();
            void SetErrors(string[] errorMessages);
            ...
            void Disable();
            void Enable();
            void Click();
            event VoidHandler OnDirty;
            void StopBinding();
        }

    At the moment, I'll focus on getting information between a Control and a single property of a Model class (say we have a textbox called "nameTextbox" that is bound to the "Name" property of a Person Model class).  The bidirectional binding of the property data to the control is done in the two methods in bold.  Calling Bind(object) will take the value from the Model object property designated by the FieldName property and make that the value of the underlying Control.  Likewise, calling ApplyChanges() will take the value of the underlying Control and push the value back into the Model object.  The workflow of screen binding is similar enough to pull most of the functionality into a ScreenElement superclass.  Here's the implementation of the Bind(object) method from ScreenElement.

     

            public virtual void Bind(object target)
            {
                try
                {
                    _target = target;
                    _originalValue = (U) Property.GetValue(target, null);
                    updateControl(_originalValue);
                }
                catch (Exception e)
                {
                    string message = string.Format("Unable to bind property " + Property.Name);
                    throw new ApplicationException(message, e);
                }
            }
     
            public void updateControl(U newValue)
            {
                // Set the latch while we're setting the initial value of the 
                // bound control
                _latched = true;
                resetControl(newValue);
                _latched = false;
            }
     
            protected abstract void resetControl(U originalValue);

    Let's say that we do have a textbox bound to the "Name" property of a Person class.  In the Bind(object) I keep a reference to the Person object that I'm binding to, then I use reflection to get the "Name" value off of the Person object, then I call updateControl() to actually set the Text property of the textbox.  To build a specific ScreenElement for a textbox I just had to override the resetControl() template method in the TextboxElement class.

     

            // BoundControl is a Textbox
            protected override void resetControl(object originalValue)
            {
                BoundControl.Text = originalValue == null ? string.Empty : _format(originalValue);
            }

    There's really not too much to it.  "_format" is a reference to a delegate that can be swapped out at configuration time to handle differences like the number of decimal points in numeric fields.  Just for completeness sake, here's the same method in the PicklistElement (the implementation of ScreenElement for comboboxes) 

            private IPicklist _list = new NulloPicklist();
     
            protected override void resetControl(object originalValue)
            {
                _list.SetValue(BoundControl, originalValue);
            }
     

    Aggregating MicroControllers

    By themselves, a single MicroController isn't all that usefull, but aggregating them together is a different story.  I use a class called ScreenBinder to perform aggregate operations across a collection of IScreenElement MicroControllers.  The public interface for IScreenBinder is down below:

     

        public interface IScreenBinder : IScreenElementDriver
        {
            void UpdateBinding();
            void FillList(string fieldName, IPicklist list);
            object BoundObject { get;}
     
            ...
     
            event VoidHandler OnChange;
            void BindScreen(object target);
            bool ApplyChanges();
            void ShowErrorMessages(Notification notification);
            void ClearErrors();
            void StopBinding();
        }

    As I said before, ScreenBinder keeps an internal ArrayList<IScreenElement> member.  When you add an IScreenElement to ScreenBinder it also adds a reference to the proper ErrorProvider for validation error display and sets up event listening for change events.  Since ScreenBinder aggregates change events for all of its IScreenElement children, you can simply listen for a single event on IScreenBinder for enabling "Submit" and "Cancel" type buttons when any element changes.

     

            public void AddElement(IScreenElement element)
            {
                // Attach the ErrorProvider to the new IScreenElement
                element.Provider = _provider;
                _elements.Add(element);
     
                // Go ahead and Bind the new IScreenElement
                if (isBound())
                {
                    element.Bind(_target);
                }
     
                // Register for all OnDirty events
                element.OnDirty += fireChanged;
            }

    Now that we have a collection of IScreenElement children, we can bind the whole collection to the Model object one child at a time.

     

     

            public void BindScreenTo(T target)
            {
                withinLatch(delegate
                                {
                                    foreach (IScreenElement element in _elements)
                                    {
                                        element.Bind(target);
                                    }
     
                                    _target = target;
                                });
            }
     
            private void withinLatch(VoidHandler handler)
            {
                _isLatched = true;
     
                handler();
     
                _isLatched = false;
            }

     

    Notice the lines of code in bold.  When the ScreenBinder is binding each IScreenElement to the Model object it sets its internal "_latch" field to true.  That's important because we don't want "IsDirty" event notifications popping up in the middle of the initial data binding.  The "latch" strategy comes into play in the method fireChanged() that raises the ScreenBinder's OnChange event.  That was a huge source of heartburn to me and my team on TradeCapture 1.  One of my core goals for the MicroController strategy on TradeCapture 2 was to systematically control the event latching in the screen synchronization.

     

            public event VoidHandler OnChange;
            private void fireChanged()
            {
                if (_isLatched)
                {
                    return;
                }
     
                if (OnChange != null)
                {
                    OnChange();
                }
            }

     

    The more predictable data binding by itself was a win, but I had other design goals as well.  The remainder of the post is a rundown of those goals and how I used MicroControllers to achieve these goals.

     

    Goal:  Make the View behavioral code easier to maintain and verify by inspection

    Like I said earlier, the design time property editor is great for writing small behavioral and formatting functionality from scratch, but can you look at a screen in the designer and "see" what's wired up to what?  I'll answer that one with "you can't."  To find out what the screen is doing, which events are wired and to what, and what screen elements are bound to which property you've got to click on all of the elements and scroll through the Properties tab in Visual Studio.  The information you need to maintain or patch the screen is scattered all over the place.  I got very frustrated on TradeCapture 1 with how hard it was to understand the behavior of complex screens.

    To combat that problem in TradeCapture 2 I wanted the wiring of the View to be compressed into a readable form without sacrificing the straightforward speed of using the designer.  Setting up all the MicroController objects was going to lead to ugly, verbose code that made the readability of the code worse.  What I ended up with is a Fluent Interface to configure MicroControllers against all the screen elements in a readable format.  To remove a little more friction, I wrote a crude codegen tool that simply spits out a class with constants for all of the public properties for my Model classes like this one below for my Trade class.

    public class TradeFields
    {
        public static readonly string Description = "Description"
        public static readonly string Status = "Status"
        public static readonly string TradeId = "TradeId"
        ...
    }

    Hey, if you have to work in a statically typed language you might as well take advantage of it right?  Having the property names in Intellisense is definitely better than strings every which way. 

    Now that I have the property names as constants I can configure a screens behavior with code like this snippet down below:

            public void Bind(IScreenBinder binder)
            {
                _binder = binder;
     
                _binder.BindProperty(TradeFields.Trader).To(traderCombobox).WithLabel(traderLabel)
                    .FillWith(ListType.Trader);
     
                _binder.BindProperty(TradeFields.Strategy).To(strategyCombobox).WithLabel(strategyLabel)
                    .FillWith(ListType.Strategy);
     
                // LegalEntity & Book
                _binder.BindProperty(TradeFields.Book).To(bookCombobox)
                    .FillWith(ListType.Book)
                    .WithLabel(bookLabel)
                    .RebindOnChange()
                    .OnChange(delegate {_presenter.BookChanged();});
     
                _binder.BindProperty(TradeFields.LegalEntity).To(legalEntityCombobox).WithLabel(legalEntityLabel);
     
                _binder.BindProperty(TradeFields.CounterParty).To(counterPartyCombobox).WithLabel(counterPartyLabel)
                    .FillWith(ListType.Counterparty);
     
                _binder.BindProperty(TradeFields.TradeDate).To(tradeDatePicker).WithLabel(tradeDateLabel)
                    .OnChange(delegate { _tradePresenter.TradeDateChanged(); });
     
            }

    In this one method I'm completely defining both the data binding from control to property and the wiring of the View to its Presenter for OnChange events (look at the two snippets of code above in bold).  I'm arguing that this type of data binding and declarative attachment of behaviors and event tagging is better for maintainability than classic designer driven Data Binding because all of the relevant functionality is boiled down into such a smaller area of the code.  I can scan this code and understand what the screen is doing and spot errors in the screen wiring.  The speed issue of the initial write is at least on par with Data Binding through the designer by simply enabling Intellisense.

    I'm not sure I really got all the way to my goal of clean, expressive language to describe the desired screen behavior because of the inherent limitations of C# 2.0.  My thinking is that this approach will shine much more in IronRuby or even in C# 3.0.  I thought a little bit about rewriting this entire data binding scheme as an open source project, but I think I'm shelving that idea indefinitely.  I do think it would be an interesting project for IronRuby and WPF someday.

     

     

    Goal:  Reuse minor screen behavior

    Since coming to New York I've worked on two different "Trade Capture" applications.  I've observed a lot of sameness of programming tasks across the screens in the two projects and I think I learned a lot of lessons from the first that have made the second more successful.  One of the things we hit in the first project was this scenario:  you have some sort of property that's set by choosing a tab or a radio button in the screen.  In TradeCapture 1 we wrote manual code that set the property on the underlying Trade object anytime the tab selection was changed.  It's subtle, but I'd almost call that an intrusion of business logic into the presentation code.  Even if you make the case that that code was definitely presentation related, it added repetitive code and noise to the View.  Much worse is the fact that that behavior wasn't covered by an automated test because we gave up early on automating tests through the screen.

    In TradeCapture 2 I saw that same scenario coming and built a MicroController for that repetitive behavior.  In this case I have several instances of an enumeration property, with a series of radio buttons representing each possible enumeration value.  In the code we need to know how to set the property anytime a radio butto