Posts Tagged ‘Design Patterns’

Refactoring with the Decorator Pattern

If you are wondering what happened to my flame-war-instigating series on the problems with MVC, you’ll have to continue waiting (as will I for the flame war, apparently). I’ve been busy and haven’t had the time to finish typing and inserting links into the rest of the posts. Such is life.

In the meantime, I hope to start emphasizing the usefulness of developing with patterns. This post was inspired by Sean Chambers recent 31 Days of Refactoring (e-book) and my recent flub when trying to describe the Decorator pattern (ducks, really?).

Setting the Stage

On a recent project using WPF and Prism, we’ve built business layer objects to import and export text and Excel files in batches. These batch processes included importing data, transforming the data into something useful, and persisting the transformed data into our database. We needed to communicate progress back to the UI for each of these tasks to keep the user aware of progress, as these tasks can take quite a long time, especially with multiple files. The initial design was raw and messy with lots of code duplication to explicitly create a BackgroundWorker directly within each ViewModel to start the import/export process and listen for events fired directly from our business objects (which essentially follow the Transaction Script pattern, more or less).

Another co-worker, when he was tasked with building another importer, created a subclass of our base ViewModel class and added all the BackgroundWorker plumbing, then did the same for our base business object class. He also created a ProgressItem : INotifyPropertyChanged type with methods to Start(int items), StartAsIndeterminate, IncrementProgress, EndWithSuccess, and EndWithFailure. He also added a collection wrapper for ProgressItems to allow ease of registering and auto-subscribing (through the AutoNotify method) the owning business object to the PropertyChanged events of the ProgressItems. With this setup, the UI ViewModel could listen to the PropertyChanged events of the business object’s ProgressItems instead of having the business object fire its own events. As you can imagine, this made implementing a batch import / export process immensely easier.

I eventually went back and refactored all of our existing business objects and ViewModels to follow this approach. Not only are both the business objects and ViewModels easier to debug, they are also easier to test since we are no longer firing events, just updating the state of a given ProgressItem. Well, sort of….

My Turn

I was recently tasked with creating a new batch import process to pull data from Excel. I started by following the pattern JB set up and had the initial steps of my batch import object ready to go. (I also confess to not having written any tests yet because, to date, we hadn’t figured out how to mock out the SpreadsheetDocument, Rows, etc. from the Open XML SDK we’re using to assist in our import / export tasks. I’ve now solved that problem and retro-fitted in unit tests. I’ll post that solution later.)

Identifying the Problem

After taking a step back to look at what I had done, I quickly realized that I was violating SRP with the inclusion of the ProgressItems in each step. Some might think that’s not such a big deal; after all, calling start, increment, and end on a single object is only three lines, which doesn’t seem like a lot. However, multiply those three lines by the number of import/export objects and factor in the number of times we forget just one of the them, and you begin to appreciate removing the extraneous bits.

I’m quite certain I noticed this primarily because of my study of functional programming rather than any object-oriented pattern literature I’ve come across. Nevertheless, I considered only OO patterns for the solution simply because the alternative was likely a monad, and that just scares the pants off of most people. (And I like my co-workers.)

The Contenders

I needed something that could pull the ProgressItem out of my actual import procedure and allow me to focus that logic purely on the import. The two patterns that came to mind were the Decorator and the Visitor.

The Decorator is generally considered (well, at least by the people I know) the simpler of the two. It wraps and extends an object without changing the underlying object and still providing the same interface. Examples include “decorating” coffee with sugar, cream, etc. and returning an adjusted price for the additional “decorations.”

The Visitor, on the other hand, is passed into an object’s void Accept(Visitor visitor) method and provides some resulting side-effect through the visitor itself. Examples include pretty printing, which print a tree-structure with the appropriate indentation, or adding the appropriate tax to an order. Another example for those using the System.Expression namespace would be using the ExpressionVisitor to allow the use of POCO objects with Entity Framework v1, as JB demonstrated here. (For those familiar with monads, you’ll likely see some resemblance.)

In this case, I had the following interface:

For reference, the initial state of a Loader looked something like this, making adjustments to the method signatures for the addition of the ProgressItem, which initially was passed to each method:

Enter the Decorator

Instead of muddying my interface with a void Accept(Visitor vistor) method, I chose to just decorate it. My resulting decorated class looked as follows:

The resulting base DetailLoader looked like so:

This made the loader much easier to reason about and test thoroughly, as the ProgressItem is completely removed. I no longer have to remember to add the calls to it or even bother with anything other than loading data. Again, I know some will probably call this an over-engineered example, but as a developer who has had to debug these things when they were initially one method directly on the business object not firing a particular event, the additional abstractions make this a breeze to create, debug, and test. To each his own.

Testing

As I mentioned, I figured out a way to test this against the Open XML SDK, but since this is already quite a long post, I’ll postpone that for later. I hope you find this a helpful explanation of how and when to refactor using the Decorator pattern. Please let me know if you have any feedback on the matter.

Domain Driven Design Presentation

Duct Tape AND Quality Together

Dogs and Cats Living Together

Dogs and Cats Living Together

You’ve probably read Joel’s post on The Duct Tape Programmer and several responses. I did not like Joel’s post at first, as I thought it far too general and easily taken in the context of “always do it this way.” For the record, I have no problems with the duct tape approach when trying something out, but I’ve been burned when having to work on someone else’s let-me-try-this project that then became a core, production system. That’s a formula for PAIN. That said, I think you can make a case for using a duct tape approach for some, small parts of your application.

This past week I put together a presentation on DDD for my office. I included some slides describing DDDD and CQS as Greg Young has discussed time and again. While I put together those slides and thinking about Bounded Contexts, I had a sudden realization that even within a single Bounded Context or Module, you could mix duct tape with quality when using CQS.

CQS

If you look at the diagram above, you can easily see where this is possible. If you split your module into read and write contexts, you can focus your greatest efforts for quality on the write side, where your domain lives, and leave the ever-changing read side to duct tape, RAD, etc. for displaying in the UI or reporting. The idea here is that you will often find that what you need to persist doesn’t change very much, but what you are asked to display changes nearly constantly. That’s at least my experience.

Another benefit to this approach is on the sales pipeline. Creating applications consists of these two parts: reading and writing. You may find that clients who have their own internal developers may not want to hire a consultant or contracting firm to build an entire app at their normal rates, but if you can provide them the write side and architecture guidance for the rest of the app, you may be able to sell more projects and keep your people happy working on quality code and quality projects. Of course, that’s just theory at this point.

So is this a case of “mass hysteria”? I don’t know. I like the idea, if not so much for the inclusion of duct tape as the possibility of limiting changes to the core domain models in an application architecture. I’m curious to know what others think or have done.

The Problem with the MVC Frameworks – Introduction

The anticipatory buzz about ASP.NET MVC last year has become a loud clanging about the general MVC pattern this year. We’ve got several people talking about the “M” in MVC (K. Scott, Rob & Javier); the “right” way to make ASP.NET MVC work (Jimmy and Seb); and complete alternatives in the form of FubuMVC (Front Controller), Bistro (Alex), and—related from a web development perspective if not MVC—OpenRasta (Seb). Why do we have all this complexity or all these options? I submit to you that the problems in the pattern as it relates to web design and the complex structures designed to handle it are a result of mixed metaphors; i.e., the web is not a UI but a service platform.

Before moving on, let me just say that by no means am I advocating WebForms or other, similar frameworks. Such things are atrocities that should never have been committed upon this earth. (Okay, I exaggerate a bit, but hopefully you get my point that while I’m about to rag on MVC, some of these other things are worse.)

As I wrote, this thing became far too long for a single post, so I’m breaking it up into sections. I also need to find and tie in the discussion I had with JB about this very thing. I like how that discussion went, although it was based upon other discussions similar to those in the following posts:

1. A History of Violence against HTML
2. New Names for Old Things
3. Serve me up some of that good ole Appl(ication)e Pie
4. The Web is a Service Bus
5. The Gauntlet

So stay tuned. There’s more to come. :)

Prism Digg/Twitter Search Client on Channel 9

The Microsoft Patterns & Practices team have posted links to the Channel 9 Prism digg/twitter search application on their CodePlex site. Check it out: patterns & practices: Composite WPF and Silverlight – Home

ViewModel Futures

Glenn Block asked two questions on Twitter tonight that were too good to pass up. First, do you want better tooling, more testable data binding, or a ViewModel base class? I agree with whoever said patterns exist to make up for faults in a language; however, in this case, I think I would choose enhancements to data binding. It’s a little too magical, imho.

I would like to see a ViewModel base eventually, though, as that would be one less thing to wire up myself, and it hopefully silence all the people complaining about the lack of a model in MVC. (Yes, I am thinking the backend models should be sharable among WPF, Silverlight, and MVC.)

Glenn’s second question related to tv target audience. I am always a fan of simple explocicity, to borrow a word from JB. I think that’s what the experts use. Also, I don’t know many who want to me mediocre some day, so going for the best and letting it trickle down is a great idea.

Just my $.02.

YAGNI–Whose Definition of Simple?

I have read a lot about YAGNI lately, especially regarding TDD. The thing that keeps bugging me is the definition of “simple.” Who defines simple? For instance, wouldn’t static methods be simpler than building objects? You could then write more functionally. Or is that not simpler to you? If you follow command-query separation, wouldn’t building everything as either pure functions or commands be simplest? JB and I have found this set of patterns immensely easy to create and test of late, especially in comparison to the ever-increasing-in-complexity procedural/OO code in place before.

So I guess my question is this: Is it really so bad to start with some basic patterns that will let you refactor more easily? I think the desire to make things as simple as possible–especially when you know you will need it–can be a waste of time and a good way of getting bad code into your source.

I know I will hear it from the Agile community that I just don’t get it, but I think I do. I really like starting simple and keeping things in nice, bite-sized testable chunks. And yes, I’m still learning. However, without a consistent and meaningful definition of “simple,” we’re likely to end up with a follow-up movement of making things complex for the sake of extensibility again.

So what do you think: is CQS too complex a starting point, or is it a nice, “simple,” and testable approach for YAGNI?

Correctly Naming Patterns

JB and I were discussing some of the patterns we were using on our current project today while working on merging some of our disparate (but completely related) code. I had created several classes named XyzBuilder with the intention of actually following the Builder pattern. My final classes are really just Strategies, but I never changed the name (though I’ve meant to do so).

This hasn’t lead to confusion, however, as (a) the “builder” is in fact “building” an object for me so the name is still meaningful and (b) most of my team members aren’t that familiar with using patterns on a daily basis (or they at least say they don’t). I’ve a thought, though, that objects with pattern-ish names should be renamed to either non-pattern names or the name of the pattern they use.

Should the name match the pattern or does it really matter?

Another Oxite Indeed

Another Oxite, indeed. My Google Reader reported a flood of activity in the AppArch CodePlex wiki, the majority of which was updated patterns pages with “BETA – Published for Community Feedback. This page is a wiki.  Please provide your feedback in the comments below,” at the top. The Application Architecture Guide, v2 is now back in beta status after the flood of community feedback following its December 2008 “final” release.

I’m glad to see Microsoft respond to the community. I find great hope in Microsoft’s future in their willingness to listen and respond. If only they would do so sooner rather than later, they would have a much better reputation with the community. Nevertheless, I’m pleased with their desire to dialogue with the community to improve their guidance.

Now, if you are an architect or developer with experience in the areas for which Microsoft is offering guidance, speak up. Help provide the response for which Microsoft is asking. This is a great opportunity for us to bridge the relationship we have with the team at Microsoft providing the tools we use daily.