Look Ma! Real Proxies...

Wednesday, December 03, 2008 3:56:17 PM (Mountain Standard Time, UTC-07:00)

I took some time today to pull down the source code for SvnBridge today, and man, I was blown away. I started at Program.cs and made it to line 25 Bootstrapper.Start(). From there I went on to look at the hand rolled container, then the ProxyFactory.

In order for me to fully grasp the System.Runtime.Remoting API for creating proxies I had to re-write the code from SVN Bridge.... I just had too... it's just how I learn. It's like tracing over cartoons when you're a kid. I still do it!

In case you're interested, the attached code is the sample I put together that is derived from the source code of SvnBridge. If you haven't checked out the source for the project, you really should.

Pretty cool stuff.... Hopefully, this helps out anyone else who's just as curious

My reduced sample source code...

private static void Main(string[] args)
{
    var marshal_mathers = new Person("marshall mathers");
    var some_celebrity = ProxyFactory.Create<IPerson>(marshal_mathers, new MyNameIsSlimShadyInterceptor());
 
    try
    {
        var name = some_celebrity.what_is_your_name();
        name.should_be_equal_to("slim shady");
    }
    catch (Exception e)
    {
        Console.Out.WriteLine(e);
    }
    Console.Out.WriteLine("will the real slim shady please stand up...");
    Console.In.ReadLine();
}

#

Container Configuration

Sunday, November 09, 2008 8:19:45 PM (Mountain Standard Time, UTC-07:00)

In my last post I briefly mentioned how we were wiring some components in to our container.  The syntax looked like the following:

            container.AddProxyOf(
                new ReportPresenterTaskConfiguration(), 
                new ReportPresenterTask(
                    Lazy.Load<IReportDocumentBuilder>(),
                    Lazy.Load<IApplicationSettings>())
                    );

We're using Castle Windsor under the hood, but we have an abstraction over it that allows us to configure it as we like. Even switching the underlying implementation. Which we did, from our hand rolled container to Castle Windsor. The implementation of the above method looks as follows:

        public void AddProxyOf<Interface, Target>(IProxyConfiguration<Interface> configuration, Target instance)
            where Target : Interface
        {
            var builder = new ProxyBuilder<Interface>();
            configuration.Configure(builder);
            AddInstanceOf(builder.CreateProxyFor(instance));
        }

Wikipedia defines the Proxy design pattern as:

A proxy, in its most general form, is a class functioning as an interface to another thing.

To understand the ProxyBuilder<Interface> implementation you can checkout JP's strongly typed selective proxies. The "AddProxyOf" method creates an instance of a proxybuilder. It then passes it to the configuration to allow it to configure the proxy builder before building the proxy. Then it registers the proxy as a singleton in to the container.

    public interface IConfiguration<T>
    {
        void Configure(T item_to_configure);
    }
    public interface IProxyConfiguration<T> : IConfiguration<IProxyBuilder<T>>
    {
    }

In this case the proxy configuration looks like:

    public class ReportPresenterTaskConfiguration : IProxyConfiguration<IReportPresenterTask>
    {
        public void Configure(IProxyBuilder<IReportPresenterTask> builder)
        {
            var constraint = builder.AddInterceptor<DisplayProgressBarInterceptor>();
            constraint.InterceptOn.RetrieveAuditReport();
        }
    }

This guy adds a progress bar interceptor, that displays a progress bar as the report is getting generated via the "RetrieveAuditReport" method on the IReportPresenterTask.

#

Lazy Loaded Interceptors

Sunday, November 09, 2008 2:55:32 PM (Mountain Standard Time, UTC-07:00)

Patterns of Enterprise Application Architecture defines Lazy Load as:

An object that doesn't contain all of the data you need but knows how to get it.

 

A while back I was trying to figure out how to lazy load objects from a container, so that I didn't need to depend on the objects dependencies needing to be wired up in the correct order. The syntax I was looking for was something like the following....

container.AddProxyOf(
    new ReportPresenterTaskConfiguration(),
    new ReportPresenterTask(
        Lazy.Load<IReportDocumentBuilder>(),
        Lazy.Load<IApplicationSettings>())
    );

Lazy.Load<T> will return a proxy in place of an actual implementation. This is just a temporary place holder that will forward the calls to the actual implementation. It wont load an instance of the actual type until the first time a call is made to it.

public class when_calling_a_method_with_no_arguments_on_a_lazy_loaded_proxy : lazy_loaded_object_context
{
    [Observation]
    public void should_forward_the_original_call_to_the_target()
    {
        target.should_have_been_asked_to(t => t.OneMethod());
    }

    protected override void establish_context()
    {
        target = dependency<ITargetObject>();

        test_container
            .setup_result_for(t => t.find_an_implementation_of<ITargetObject>())
            .will_return(target)
            .Repeat.Once();
    }

    protected override void because_of()
    {
        var result = Lazy.Load<ITargetObject>();
        result.OneMethod();
    }

    private ITargetObject target;
}

So when the method "OneMethod" is called on the proxy. It should forward the call to the target, which can be loaded from the container. The implementation depends on Castle DynamicProxy, and looks like the following...

public static class Lazy
{
    public static T Load<T>() where T : class
    {
        return create_proxy_for<T>(create_interceptor_for<T>());
    }

    private static LazyLoadedInterceptor<T> create_interceptor_for<T>() where T : class
    {
        Func<T> get_the_implementation = resolve.dependency_for<T>;
        return new LazyLoadedInterceptor<T>(get_the_implementation.memorize());
    }

    private static T create_proxy_for<T>(IInterceptor interceptor)
    {
        return new ProxyGenerator().CreateInterfaceProxyWithoutTarget<T>(interceptor);
    }
}

internal class LazyLoadedInterceptor<T> : IInterceptor
{
    private readonly Func<T> get_the_implementation;

    public LazyLoadedInterceptor(Func<T> get_the_implementation)
    {
        this.get_the_implementation = get_the_implementation;
    }

    public void Intercept(IInvocation invocation)
    {
        var method = invocation.GetConcreteMethodInvocationTarget();
        invocation.ReturnValue = method.Invoke(get_the_implementation(), invocation.Arguments);
    }
}

public static class func_extensions
{
    public static Func<T> memorize<T>(this Func<T> item) where T : class
    {
        T the_implementation = null;
        return () => {
                   if (null == the_implementation) {
                       the_implementation = item();
                   }
                   return the_implementation;
               };
    }
}

"resolve" is a static gateway to the underlying IDependencyRegistry. This idea was totally inspired by JP's strongly typed selective proxies. If you haven't already, you should definitely check it out.

Download the source.

#

Intercepting Business Transactions

Monday, November 03, 2008 8:02:01 PM (Mountain Standard Time, UTC-07:00)

In Patterns of Enterprise Application Architecture, the Unit of Work design pattern is defined as:

Maintains a list of objects affected by a business transaction and coordinates the writing out of changes and the resolution of concurrency problems.

NHibernate seems to have a great implementation of the unit of work, but understanding when to start and commit the unit of work without repeating yourself can be a little tricky. One thing we've been doing is starting a unit of work using an interceptor.

[Interceptor(typeof (IUnitOfWorkInterceptor))]
public class AccountTasks : IAccountTasks
{
    public bool are_valid(ICredentials credentials)
    {
        ...
    }
}

Account tasks is a service layer piece, that is decorated with an interceptor that will begin and commit a unit of work.

public interface IUnitOfWorkInterceptor : IInterceptor
{}

public class UnitOfWorkInterceptor : IUnitOfWorkInterceptor
{
    private readonly IUnitOfWorkFactory factory;

    public UnitOfWorkInterceptor(IUnitOfWorkFactory factory)
    {
        this.factory = factory;
    }

    public void Intercept(IInvocation invocation)
    {
        using (var unit_of_work = factory.create()) {
            invocation.Proceed();
            unit_of_work.commit();
        }
    }
}

The interceptor starts a new unit of work, before proceeding with the invocation. If no exceptions are raised the unit of work is committed. If a unit of work is already started, the unit of work factory returns an empty unit of work. This ensures that if a service layer method calls into another method that it doesn't start another unit of work.

public interface IUnitOfWorkFactory : IFactory<IUnitOfWork>
{}

public class UnitOfWorkFactory : IUnitOfWorkFactory
{
    private readonly IApplicationContext context;
    private readonly IDatabaseSessionFactory factory;
    private readonly TypedKey<ISession> key;

    public UnitOfWorkFactory(IApplicationContext context, IDatabaseSessionFactory factory)
    {
        this.context = context;
        this.factory = factory;
        key = new TypedKey<ISession>();
    }

    public IUnitOfWork create()
    {
        if (unit_of_work_is_already_started()) {
            return new EmptyUnitOfWork();
        }

        return create_a_unit_of_work().start();
    }

    private bool unit_of_work_is_already_started()
    {
        return context.contains(key);
    }

    private IUnitOfWork create_a_unit_of_work()
    {
        var session = factory.create();
        context.add(key, session);
        return new UnitOfWork(session, context);
    }
}

The implementation of the repository pulls the active session from the application context.

public class DatabaseRepository<T> : IRepository<T>
{
    private readonly IApplicationContext context;
    private readonly IKey<ISession> session_key;

    public DatabaseRepository(IApplicationContext context)
    {
        this.context = context;
        session_key = new TypedKey<ISession>();
    }

    public IQueryable<T> all()
    {
        return the_current_session().Linq<T>();
    }

    public void save(T item)
    {
        the_current_session().SaveOrUpdate(item);
    }

    public void delete(T item)
    {
        the_current_session().Delete(item);
    }

    private ISession the_current_session()
    {
        var current_session = context.get_value_for(session_key);
        if (null == current_session || !current_session.IsOpen) {
            throw new NHibernateSessionNotOpenException();
        }
        return current_session;
    }
}
For more information on Interceptors check out the Castle stack...

#

Collecting Errors

Tuesday, October 28, 2008 9:10:52 AM (Mountain Standard Time, UTC-07:00)

Validation is a tough subject. One that I'm constantly trying to think of better ways of doing. Some suggest that all validation should occur in the domain, and some prefer to check if the object is valid before proceeding. I lean towards the idea of not allowing your objects to enter an invalid state. So far the easiest approach I have found to do this is to raise meaningful exceptions in the domain to ensure this.

However, when there are several reasons why an object can be considered "invalid" and, those reasons need to be reflected in the UI, I haven't been able to figure out a clean way to do this in the domain. Suggestions are welcome.

Here's an approach that we've taken to some of our validation, when user input needs to be checked so that we can provide meaningful error messages to the end user.

First we have 2 core validation interfaces:

public interface IValidationResult
{
    bool IsValid { get; }
    IEnumerable<string> BrokenRules { get; }
}

and

public interface IValidation<T>
{
    IValidationResult Validate(T item);
}

The IValidation<T> is in essence a form of a Specification. Now to collect the errors we use a visitor. The following are the core visitor interfaces.

public interface IVisitor<T>
{
    void Visit(T item_to_visit);
}
public interface IValueReturningVisitor<TypeToVisit, TypeToReturn> : IVisitor<TypeToVisit>
{
    void Reset();
    TypeToReturn Result { get; }
}

We have an implementation of a IValueReturningVisitor that collects errors from visiting IValidations, then returns a validation result.

public class ErrorCollectingVisitor<T> : IValueReturningVisitor<IValidation<T>, IValidationResult>
{
    private readonly T item_to_validate;
    private readonly List<string> results;

    public ErrorCollectingVisitor(T item_to_validate)
    {
        this.item_to_validate = item_to_validate;
        results = new List<string>();
    }

    public void Visit(IValidation<T> item_to_visit)
    {
        var validation_result = item_to_visit.Validate(item_to_validate);
        if (!validation_result.IsValid)
        {
            results.AddRange(validation_result.BrokenRules);
        }
    }

    public void Reset()
    {
        results.Clear();
    }

    public IValidationResult Result
    {
        get { return new ValidationResult(results.Count == 0, results); }
    }
}

And a handy extension method for returning the value from visiting a set of validations.

public static Result ReturnValueFromVisitingAllItemsWith<TypeToVisit, Result>(
    this IEnumerable<TypeToVisit> items_to_visit, IValueReturningVisitor<TypeToVisit, Result> visitor)
{
    visitor.Reset();
    items_to_visit.Each(x => visitor.Visit(x));
    return visitor.Result;
}

An example of the usage for the visit can be seen below:

public IValidationResult Validate(IUser user)
{
    return userValidations
        .Select(x => x as IValidation<IUser>)
        .ReturnValueFromVisitingAllItemsWith(new ErrorCollectingVisitor<IUser>(user));
}

#

Recursive Command

Friday, August 01, 2008 8:37:35 AM (Mountain Standard Time, UTC-07:00)

When building up a tree view that represents the directory structure of a file system, like the windows explorer, my first reaction was to use recursion to traverse the file system and build up a tree. I quickly found that doing something like that is a time consuming process, and required some optimization.

I came up with what I like to call the recursive command. Each Tree Node item on a tree view is bound to a command to execute. The command looks like this...

public interface ITreeNodeClickedCommand {
    void Execute(ITreeNode node);
}

When the command is executed, the command gets an opportunity to modify the state of the tree node that was clicked. In this case I wanted to lazy load the sub directories of a node that was clicked. The command implementation looks like this...

public interface IAddFoldersCommand : ITreeNodeClickedCommand {}

public class AddFoldersCommand : IAddFoldersCommand {
    private readonly DirectoryInfo the_current_directory;
    private bool has_executed;

    public AddFoldersCommand(DirectoryInfo the_current_directory) {
        this.the_current_directory = the_current_directory;
    }

    public void Execute(ITreeNode node) {
        if (!has_executed) {
            foreach (var directory in the_current_directory.GetDirectories()) {
                node.Add(new TreeNodeItem(directory.Name, ApplicationIcons.Folder, new AddFoldersCommand(directory)));
            }
        }
        has_executed = true;
    }
}

This command is executed each time the tree node that it is bound too is clicked, but will only build up the child tree node items once. Each of the child tree nodes are bound to a new instance of the same command. Hence, what I like to call the recursive command.

recursive_command

For more information on the command pattern check out WikiPedia's write up.

*Update 11:30 am MST, Friday, August. 01, 2008

After a little more inspection, I realized I was doing nothing more than just visiting each tree node item on the demand. Visitors are known to be great for recursive structures.... so ix-nay on the ecursive-ray ommand-kay.

The revised version:

public interface IAddFoldersToTreeVisitor : ITreeNodeVisitor
{
}

public class AddFoldersToTreeVisitor : IAddFoldersToTreeVisitor
{
    private readonly DirectoryInfo the_current_directory;
    private bool has_executed;
    private readonly IAddFilesToTreeVisitor add_files_visitor;
    private readonly IAddFoldersCommandFactory factory;

    public AddFoldersToTreeVisitor(DirectoryInfo the_current_directory, IAddFoldersCommandFactory factory,
                                   IAddFilesToTreeVisitor add_files_visitor)
    {
        this.the_current_directory = the_current_directory;
        this.factory = factory;
        this.add_files_visitor = add_files_visitor;
    }

    public void Visit(ITreeNode node)
    {
        if (!has_executed)
        {
            foreach (var directory in the_current_directory.GetDirectories())
            {
                node.Add(directory.Name, ApplicationIcons.Folder, factory.CreateFor(directory));
            }
            add_files_visitor.PreparedWith(the_current_directory);
            add_files_visitor.Visit(node);
        }
        has_executed = true;
    }
}

#

Hangin' Out With The Gang Of Four

Saturday, February 23, 2008 7:35:34 PM (Mountain Standard Time, UTC-07:00)

I just finished reading...

Design Patterns: Elements of Reusable Object-Oriented Software (Addison-Wesley Professional Computing Series)
by Erich Gamma, Richard Helm, Ralph Johnson, John M. Vlissides

Read more about this title...

It's about time I read this book... This catalog contains 23 patterns with examples in C++. I enjoyed reading this book. I found at times that my mind started to drift off, but then there were moments when I would forget where I was and miss my bus stop. (Ok one moment!)

I enjoyed reading the discussion on OO more then anything else in this book. The examples are a little dated but for it's time the catalog is awesome. Although I've been wanting to read this book for a while I preferred "Head First Design Patterns", mostly because it was easy to read. (I call it the comic book for dev's)

As usual, here are some quotes from the book that I really enjoyed.

"When an abstraction can have one of several possible implementations, the usual way to accommodate them is to use inheritance. An abstract class defines the interface to the abstraction, and concrete subclasses implement it in different ways. But this approach isn't always flexible enough. Inheritance binds an implementation to the abstraction permanently, which makes it difficult to modify, extend and reuse abstractions and implementations independently."

"Studies of expert programmers for conventional languages have shown that knowledge and experience isn't organized simply around syntax but in larger conceptual structures such as algorithms, data structures and idioms, and plans for fulfilling a particular goal. Designers probably don't think about the notation they're using for recording the design as much as they try to match the current design situation against plans, algorithms, data structures, and idioms they have learned in the past."

"These design patterns can also make you a better designer. They provide solutions to common problems. If you work with object-oriented systems long enough, you'll probably learn these design patters on your own. But reading the book will help you learn them much faster. Learning these patterns will help a novice act more like an expert."

"To continue to evolve, the software must be reorganized in a process known as refactoring. This is the phase in which frameworks often emerge. Refactoring involves tearing apart classes into special- and general-purpose components, moving operations up or down the class hierarchy, and rationalizing the interfaces of classes. This consolidation phase produces many new kinds of objects, often by decomposing existing objects and using object composition instead of inheritance. Hence black-box reuse replaces white-box reuse. The continual need to satisfy more requirements along with the need for more reuse propels object-oriented software through repeated phases of expansion and consolidation - expansion as new requirements are satisfied, and consolidation as the software becomes more general."

#

Replace Enum With Flyweights

Saturday, February 23, 2008 11:08:21 AM (Mountain Standard Time, UTC-07:00)

I've got a beef with enums. When I see them, I cringe... which is quite different from my days in C, where I couldn't live without enums and structs. That's another story...

"Flyweight: Use sharing to support large numbers of fine-grained objects efficiently" - Design Patterns

Design Patterns: Elements of Reusable Object-Oriented Software (Addison-Wesley Professional Computing Series)
by Erich Gamma, Richard Helm, Ralph Johnson, John M. Vlissides

Read more about this title...

Why do some of us quickly jump to enums? In procedural languages it makes sense. It's giving a type code a human readable meaning. So instead of having to stare at type code 1, everywhere you can use State.Acknowledgement, which is a lot easier to understand ... what does 1 mean again?

But in an OO language, I feel dirty when I see enums. The argument of using it for bitwise operations and the Flags attribute is weak. Create a composite!

    [Flags]
    public enum Digits {
        Zero = 0x00,
        One = 0x01,
        Two = 0x02,
        Three = 0x03,
        Four = 0x04,
        Five = 0x05,
        Six = 0x06,
        Seven = 0x07,
        Eight = 0x08,
        Nine = 0x09
    }
    [Test]
    public void Should_be_equal_to_2_digits() {
        Digits digits = Digits.Six | Digits.One;
        Assert.IsTrue( Digits.Six == (digits & Digits.Six) );
        Assert.IsTrue( Digits.One == (digits & Digits.One) );            
    }

Weak... do you really want to use a bitwise & to check if a certain digit is enabled. I don't. I'm going to use the following 2 tests to squash the enum into a first class component, with some smarts to it.

        [Test]
        public void should_be_able_to_add_a_single_digit() {
            INumberBuilder builder = CreateSUT( );
            builder.Add( Digits.One );
            Assert.AreEqual( new Number( 1 ), builder.Build( ) );
        }

        [Test]
        public void should_be_able_to_form_a_number_with_more_than_one_digit() {
            INumberBuilder builder = CreateSUT( );
            builder.Add( Digits.One );
            builder.Add( Digits.Nine );
            Assert.AreEqual( new Number( 19 ), builder.Build( ) );
        }

My current NumberBuilder implementation looks like this (it sucks but it works):

    public class NumberBuilder : INumberBuilder {
        public void Add( Digits digit ) {
            numberBeingBuilt += Convert.ToString( Convert.ToInt32( digit ) );
        }

        public INumber Build() {
            return new Number( Convert.ToInt32( numberBeingBuilt ) );
        }

        private string numberBeingBuilt;
    }

I'm going to start off by creating some Flyweights.

    public class Digits {
        public static readonly IDigit Eight = new Digit( 8 );
        public static readonly IDigit Five = new Digit( 5 );
        public static readonly IDigit Four = new Digit( 4 );
        public static readonly IDigit Nine = new Digit( 9 );
        public static readonly IDigit One = new Digit( 1 );
        public static readonly IDigit Seven = new Digit( 7 );
        public static readonly IDigit Six = new Digit( 6 );
        public static readonly IDigit Three = new Digit( 3 );
        public static readonly IDigit Two = new Digit( 2 );
        public static readonly IDigit Zero = new Digit( 0 );

        public class Digit : IDigit {
            public Digit( int digitToRepresent ) {
                _digitToRepresent = digitToRepresent;
            }

            public override string ToString() {
                return _digitToRepresent.ToString( );
            }

            private readonly int _digitToRepresent;
        }
    }

My compiler is telling me that the Add method on my builder currently accepts a parameter of type "Digits", so I'm going to change the signature to accept a parameter of type IDigit.

    public interface INumberBuilder {
        void Add( Digits digit );
        INumber Build();
    }

To...

    public interface INumberBuilder {
        void Add( IDigit digit );
        INumber Build();
    }

Let's update the NumberBuilder implementation to:

    public class NumberBuilder : INumberBuilder {
        public NumberBuilder() {
            _digitsOfNumberBeingBuilt = new List< IDigit >( );
        }

        public void Add( IDigit digit ) {
            _digitsOfNumberBeingBuilt.Add( digit );
        }

        public INumber Build() {
            return new Number( CreateIntegerFrom( _digitsOfNumberBeingBuilt ) );
        }

        private int CreateIntegerFrom( IEnumerable< IDigit > digitsOfNumberBeingBuilt ) {
            StringBuilder builder = new StringBuilder( );
            foreach ( IDigit digit in digitsOfNumberBeingBuilt ) {
                builder.Append( digit );
            }
            return Convert.ToInt32( builder.ToString( ) );
        }

        private IList< IDigit > _digitsOfNumberBeingBuilt;
    }

I run the tests and they pass, sweet. But I'm not happy with the current implementation, so I look for other potential refactorings. I decide to forward the digit to append right to the number, the number can take care of how to append the digit, rather then having the builder doing so. The builder now looks like:

    public class NumberBuilder : INumberBuilder {
        public NumberBuilder() {
            _numberBeingBuilt = new Number( 0 );
        }

        public void Append( IDigit digit ) {
            _numberBeingBuilt = _numberBeingBuilt.Append( digit );
        }

        public INumber Build() {
            return _numberBeingBuilt;
        }

        private INumber _numberBeingBuilt;
    }

And Number looks like:

    public class Number : INumber, IEquatable< Number > {
        public Number() : this( 0 ) {}

        public Number( int numberToRepresent ) {
            _numberToRepresent = numberToRepresent;
        }

        public INumber Append( IDigit digit ) {
            return new Number( ( _numberToRepresent*10 ) + digit.Value( ) );
        }

        public bool Equals( Number number ) {
            if ( number == null ) {
                return false;
            }
            return _numberToRepresent == number._numberToRepresent;
        }

        public override string ToString() {
            return _numberToRepresent.ToString( );
        }

        public override bool Equals( object obj ) {
            if ( ReferenceEquals( this, obj ) ) {
                return true;
            }
            return Equals( obj as Number );
        }

        public override int GetHashCode() {
            return _numberToRepresent;
        }

        private readonly int _numberToRepresent;
    }

To wrap this up, Number aggregates digits, the enum got dropped and was replaced by a class. There's still more refactorings that can occur, but the point is that a full blown component is much easier to extend then an enum...

For more info check out "Replace Type Code with Class" from...

Refactoring: Improving the Design of Existing Code (The Addison-Wesley Object Technology Series)
by Martin Fowler, Kent Beck, John Brant, William Opdyke, Don Roberts

Read more about this title...

 Soure:

#

Controlling Pages

Friday, February 01, 2008 4:10:39 PM (Mountain Standard Time, UTC-07:00)

WebForms is an awkward marriage between a Page Controller and a Template View. In the Web Forms model the Template View (aspx page) inherits from the Page Controller (code behind).

Patterns of Enterprise Application Architecture defines the Page Controller as:

"An object that handles a request for a specific page or action on a web site." - PoEAA

In this example I've separated the Page Controller from the Template View, because... mostly because I was bored and thought this would be a great way to better understand the patterns. So let's get started...

I defined a layer super type for all page controllers defined as :

    public interface IPageController : IHttpHandler {
        void Execute();
    }

The IPageController could have very well been called and Page Command because in this implementation I'm not concerned about having separate behaviors for GET and POST method requests. If this example were to evolve I might choose to separate the "Execute()" method into "ProcessGetRequest()" and "ProcessPostRequest()".

The IPageController type inherits IHttpHandler in order to register this page controller with ASP.NET to receive all requests for a particular path. In this case this handler is registered in the web.config for all requests to the "DisplayAllCustomers.aspx" page.

    <httpHandlers>
        <add 
            verb="*" 
            path="DisplayAllCustomers.aspx" 
            validate="false" 
            type="PlayingWithPageControllers.Web.Controllers.DisplayAllCustomersController, PlayingWithPageControllers"/>
    </httpHandlers>

If I wanted to get a little more nitty, gritty I could have specified only GET Http method's are handled by this handler.

Moving on.... The PageController base type for all controllers looks like:

    public abstract class PageController : IPageController {
        public void ProcessRequest( HttpContext context ) {
            Execute( );
        }

        public bool IsReusable {
            get { return true; }
        }

        public abstract void Execute();
    }

And finally our "DisplayAllCustomersController" component looks like:

    public class DisplayAllCustomersController : PageController, IDisplayAllCustomersController {
        public DisplayAllCustomersController( IDisplayAllCustomersView view, ICustomerTasks tasks ) {
            _view = view;
            _tasks = tasks;
        }

        public override void Execute() {
            _view.AddToBag( _tasks.AllCustomers( ) );
            _view.Render( );
        }

        private readonly IDisplayAllCustomersView _view;
        private readonly ICustomerTasks _tasks;
    }

And voila all requests to "DisplayAllCustomers.aspx" are handled by the DisplayAllCustomersController which pulls information from the model and fires it off to the template view to be rendered.

The Template View Pattern is defined as:

"Renders information into HTML by embedding markers in an HTML page." - PoEAA

Our template view for "AllCustomers.aspx" looks like this:

    <table>
        <thead>
            <tr>
                <td>First Name:</td>
                <td>Last Name:</td>
            </tr>
        </thead>
        <tbody>            
            <% foreach ( DisplayCustomerDTO dto in ViewBagLocator.For( ViewBagKeys.DisplayCustomers ) ) {%>
            <tr>
                <td><%= dto.FirstName() %></td>
                <td><%= dto.LastName( ) %></td>
            </tr>
            <% } %>
        </tbody>
    </table>

This separates the Template view from having any knowledge of the Page Controller. The Page controller has the responsibility of pulling information from the model to pass along to the appropriate view.

All access to the current context and the ASP.NET pipeline has been isolated to the HttpGateway which abstracts the ASP.NET facilities available through a condensed client interface.

    public interface IHttpGateway {
        void RedirectTo( IView view );

        void AddItemWith< T >( IViewBagKey< T > key, T itemToAddToBag );

        T FindItemFor< T >( IViewBagKey< T > key );
    }

Now that I think about it, another step that I could have taken would have to shield the page controllers from having any knowledge of "IHttpHandler", which would have further isolated the ASP.NET infrastructure from the rest of the web presentation layer.

Patterns of Enterprise Application Architecture defines a Gateway as:

"An object that encapsulates access to an external system or resource." - PoEAA

    public class HttpGateway : IHttpGateway {
        public HttpGateway( IHttpContext context ) {
            _context = context;
        }

        public void RedirectTo( IView view ) {
            _context.Server.Transfer( view.Path( ) );
        }

        public void AddItemWith< T >( IViewBagKey< T > key, T itemToAddToBag ) {
            _context.Items.Add( key, itemToAddToBag );
        }

        public T FindItemFor< T >( IViewBagKey< T > key ) {
            return ( T )_context.Items[ key ];
        }

        private readonly IHttpContext _context;
    }

If you haven't already you should go buy and read, then re-read, then re-read "Patterns of Enterprise Application Architecture by Martin Fowler"

Patterns of Enterprise Application Architecture (The Addison-Wesley Signature Series)
by Martin Fowler

Read more about this title...

Source: DOWNLOAD THE CODE

#

The Event Aggregator

Tuesday, December 18, 2007 2:26:11 PM (Mountain Standard Time, UTC-07:00)

I'd like to talk to you for a moment about my man The Event Aggregator. (Homeboy's been tossin' events for years!)

Martin Fowler defines the Event Aggregator as:

"Channel events from multiple objects into a single object to simplify registration for clients." - Martin Fowler

But he's so much more then that! This pattern comes in handy in state-ful environments, so.. hello WinForms/WPF. Sorry ASP.NET!

What this guy does is creates a single channel to find out what's going on and to raise events. Through the event aggregator you can subscribe to known events in the system as well as raise known events in the system.

Some examples for system wide events are Save, Loading, Shutdown. You can also create concepts for layer specific event aggregators that target certain layers of a system. For example UI only.

    public class ApplicationEvents {
        private static readonly IEventAggregator aggregator;
        public static readonly IEvent Save = new EventRaiser( "Save" );
        public static readonly IEvent Loading = new EventRaiser( "Loading" );

        static ApplicationEvents( ) {
            aggregator = new EventAggregator( );
            aggregator.Register( Save );
            aggregator.Register( Loading );
        }

        public static void Raise( IEvent eventToRaise ) {
            aggregator.RaiseEvent( eventToRaise );
        }

        public static void SubscribeTo( IEvent eventToSubscribeTo, EventHandler handler ) {
            aggregator.AddHandler( eventToSubscribeTo.Name, handler );
        }
    }

The ApplicationEvents becomes the central point for raising and subscribing to known application wide events. Type can be coupled to the aggregator but not to each other.

Let's start with the concept of a named event. An event is really nothing more then a delegate. In .NET there are 2 delegate signatures that are used for all events. The generic and non generic version of the EventHandler delegate. (Read More... )

A named event is an event with a name. He might look something like this guy?

    internal class EventRaiser : IEvent {
        public EventRaiser( string name ) {
            _name = name;
            _handlers = new List< EventHandler >( );
        }

        public string Name {
            get { return _name; }
        }

        public void Add( EventHandler handler ) {
            _handlers.Add( handler );
        }

        public void Raise( ) {
            Raise( null, null );
        }

        public void Raise( object sender, EventArgs data ) {
            foreach ( EventHandler handler in _handlers ) {
                if ( handler != null ) {
                    handler( sender, data );
                }
            }           
        }

        private readonly string _name;
        private readonly IList< EventHandler > _handlers;
    }

Underneath the hood it's the aggregator that's maintaining references to all the types that have subscribed to events.

    public class EventAggregator : IEventAggregator {
        public EventAggregator( ) {
            _events = new Dictionary< string, IEvent >( );
        }

        public void Register( string eventName ) {
            Register( new EventRaiser( eventName ) );
        }

        public void Register( IEvent eventToAdd ) {
            EnsureEventHasntBeenRegistered( eventToAdd );
            _events.Add( eventToAdd.Name, eventToAdd );
        }

        public void AddHandler( string eventName, EventHandler handler ) {
            RetrieveEvent( eventName ).Add( handler );
        }

        public void RaiseEvent( string withEventName ) {
            RaiseEvent< EventArgs >( withEventName, null, EventArgs.Empty );
        }

        public void RaiseEvent( IEvent eventToRaise ) {
            RaiseEvent< EventArgs >( eventToRaise.Name, null, EventArgs.Empty );
        }

        public void RaiseEvent< T >( string withEventName, object sender, T data ) where T : EventArgs {
            RetrieveEvent( withEventName ).Raise( sender, data );
        }

        private IEvent RetrieveEvent( string eventName ) {
            if ( _events.ContainsKey( eventName ) ) {
                return _events[ eventName ];
            }
            throw new ArgumentNullException( eventName, "The Event Has Not Been Registered." );
        }

        private void EnsureEventHasntBeenRegistered( IEvent eventToAdd ) {
            if ( _events.ContainsKey( eventToAdd.Name ) ) {
                throw new ArgumentException( "Event name has already been registered", eventToAdd.Name );
            }
        }

        private readonly IDictionary< string, IEvent > _events;
    }

The concept is similar to Juval Lowy's EventHelper class defined in...

Programming .NET Components, 2nd Edition
by Juval Lowy

Read more about this title...

#

The Identity Map

Tuesday, December 18, 2007 12:21:21 PM (Mountain Standard Time, UTC-07:00)

This week while I'm at home on holidays, I've been reading...

Patterns of Enterprise Application Architecture (The Addison-Wesley Signature Series)
by Martin Fowler

Read more about this title...

This book is amazing, I could probably read it over and over again. The patterns that it presents makes a lot of sense, the actual implementations and examples could probably re-vamped but I'm finding that it's a great starter to trying to understand the concepts.

So today I'm trying to grok this concept of the "IDENTITY MAP". The book defines it as:

"Ensures that each object gets loaded only once by keeping every loaded object in a map. Looks up objects using the map when referring to them."

I put together a quick implementation that I'm using for an assignment I'm writing for school. I'm creating repositories that have 2 dependencies. First dependency is a Data Mapper (not to be confused with a Mapper) and the second is an Identity Map.

As objects are requested from the repository, the repository is checking the identity map to see if an instance has been loaded, if it has it's immediately returned to the caller. If the object is not in the map the repository leverages the data mapper to load the object, then adds it to the map and returns it to the caller.

The Data Mapper is defined as:

"A layer of Mappers that moves data between objects and a database while keeping them independent of each other and the mapper itself." - PoEAA

I created a Layer Supertype to register objects in the map. The Domain Layer Super type demands that domain objects had an ID. The ID is what's getting used to load and register objects into the map.

The Layer Supertype is defined as:

"A type that acts as a the supertype for all types in it's layer." - PoEAA

The Domain Layer Super Type.

    public interface IDomainObject {
        long ID();
    }

My actual implementation of the identity map looks like this...

    public class IdentityMap< T > : IIdentityMap< T > where T : IDomainObject {
        public IdentityMap() {
            _items = new List< T >( );
        }

        public void Add( T domainObject ) {
            EnsureObjectHasNotAlreadyBeenAdded( domainObject );
            _items.Add( domainObject );
        }

        public T FindObjectWithIdOf( long idOfObjectToFind ) {
            foreach ( T item in _items ) {
                if ( item.ID( ).Equals( idOfObjectToFind ) ) {
                    return item;
                }
            }
            return default( T );
        }

        private void EnsureObjectHasNotAlreadyBeenAdded( T domainObject ) {
            if ( ContainsObjectWithIdOf( domainObject.ID( ) ) ) {
                throw new ObjectAlreadyAddedToIdentityMapException( domainObject );
            }
        }

        private readonly IList< T > _items;
    }

One of the benefits I like about the Identity Map is that it acts as an in memory cache for objects loaded from the database. This reduces the number of trips to and from the persistence store.

Source Code

#

The Visitor Pattern

Friday, November 16, 2007 11:00:13 PM (Mountain Standard Time, UTC-07:00)

One of the many cool things we learned last week was on how to traverse a collection using a visitor.

"...the visitor design pattern is a way of separating an algorithm from an object structure. A practical result of this separation is the ability to add new operations to existing object structures without modifying those structures." - wikipedia

Let's pretend that I've got an exam, and this exam has a bunch of questions and I want to find out how many questions have been completed.

I could throw a method on my IExam type that returns the number of completed questions. Kind of like...

    public class BadExam : IExam {
        public BadExam( ) : this( new List< IQuestion >( ) ) {}

        public BadExam( IList< IQuestion > questions ) {
            _questions = questions;
        }

        public int GetCompletedQuestions( ) {
            int completedQuestions = 0;
            foreach ( IQuestion question in _questions ) {
                completedQuestions += question.IsComplete( ) ? 1 : 0;
            }
            return completedQuestions;
        }

        private IList< IQuestion > _questions;
    }

 

But what happens when I want to find out other statistics about the questions in my exam. I could add additional methods to the IExam type for each type of information that I want to query on, but this would totally violate the Open/Closed Principle.

Let's try to solve the same problem above using a visitor...

    public class Exam : IExam {
        public Exam( ) : this( new List< IQuestion >( ) ) {}

        public Exam( IList< IQuestion > questions ) {
            _questions = questions;
        }

        public void TraverseUsing( IVisitor< IQuestion > visitor ) {
            foreach ( IQuestion question in _questions ) {
                visitor.Visit( question );
            }
        }

        private IList< IQuestion > _questions;
    }

What this allows me to do is create new implementations of IVisitor's that traverse the collection of questions but collect information that it needs.

For example we could have a "CompletedQuestionsVisitor" that keeps track of the number of completed questions.

    public class CompletedQuestionsVisitor : ICompletedQuestionsVisitor {
        private int _completedQuestions;

        public void Visit( IQuestion question ) {
            _completedQuestions += ( question.IsComplete( ) ? 1 : 0 );
        }

        public int TotalCompletedQuestions( ) {
            return _completedQuestions;
        }
    }

Now I can traverse the internal collection of questions and pick out the information that I need.

What if I wanted to build a tree of specifications and wanted to traverse a collection of items and keep track of only those items that match my composite specification. Introducing the "Specification Visitor".

    public class SpecificationVisitor< T > : ISpecificationVisitor< T > {
        private readonly ISpecification< T > _specification;
        private int _totalMatching;

        public SpecificationVisitor( ISpecification< T > specification ) {
            _specification = specification;
        }

        public void Visit( T item ) {
            _totalMatching += _specification.IsSatisfiedBy( item ) ? 1 : 0;
        }

        public int TotalMatching( ) {
            return _totalMatching;
        }
    }

Yes it's a little overboard and slightly contrived, but perhaps someone can find a good home for him.

Source Code (2.28MB)

#

Decorating Services

Saturday, October 27, 2007 9:41:19 PM (Mountain Standard Time, UTC-07:00)

So tonight I decided to spend some time playing with services, principals, identities, and loggers. On Thursday at work a client wanted to be able to log several different events in a system. I remember a while back reading an article on MSDN by Oren on Ioc, and I thought I would try to roll something out just to get a feel for who it could work. I still have a lot to learn when it comes to IoC so I put that aside for now.

It all starts at the "AuthenticationService" in a method called "CheckCredentials". It looks something like...

        public bool CheckCredentials( string userName, string password ) {
            IUser user = _repository.FindBy( userName );
            if ( IsMatch( user.Password, password ) ) {
                ApplyPrincipalToThreadFor( user );
                return true;
            }
            return false;
        }
 

This method checks the repository for the user with the matching username and checks to see if the password given matches what's stored for the user in the repository. If it does, a principal is created and applied to the current thread. Passwords really shouldn't be held in memory for long, and would probably better be transferred or computed as a hash, so that the actual password exposure is limited. (There's also a "SecureString" type which I haven't spent much time looking at, but sounds promising!)

Now if I wanted to log all login attempts I can extend this service with a AuthenticationLoggerService decorator. That looks like... 

    public class AuthenticationLoggerService : IAuthenticationService {
        public AuthenticationLoggerService( IAuthenticationService service, ILogger logger ) {
            _service = service;
            _logger = logger;
        }
 
        public bool CheckCredentials( string userName, string password ) {
            _logger.Write( "User Login Attempt: " + userName );
            return _service.CheckCredentials( userName, password );
        }
 
        private readonly IAuthenticationService _service;
        private readonly ILogger _logger;
    }

All this type does is log information and delegate to the actual type.

"The Decorator Pattern attaches additional responsibilities to an object dynamically. Decorators provide flexible alternative to subclassing for extending functionality." - Head First Design Patterns

Read more in...

Head First Design Patterns (Head First)
by Elisabeth Freeman, Eric Freeman, Bert Bates, Kathy Sierra

Read more about this title...

PlayingWithServices.zip (2.28 MB)

#

SALES TAXES

Monday, September 24, 2007 7:07:23 PM (Mountain Standard Time, UTC-07:00)

I recently came across a problem, and I thought I would try to flex some of my developer muscle to try to solve it. The problem reads as follows:

Basic sales tax is applicable at a rate of 10% on all goods, except books,
food, and medical products that are exempt. Import duty is an additional
sales tax applicable on all imported goods at a rate of 5%, with no
exemptions.

When I purchase items I receive a receipt which lists the name of all the
items and their price (including tax), finishing with the total cost of the
items, and the total amounts of sales taxes paid.  The rounding rules for
sales tax are that for a tax rate of n%, a shelf price of p contains
(np/100 rounded up to the nearest 0.05) amount of sales tax.

Write an application that prints out the receipt details for these shopping
baskets...
INPUT:_

Input 1:
1 book at 12.49
1 music CD at 14.99
1 chocolate bar at 0.85

Input 2:
1 imported box of chocolates at 10.00
1 imported bottle of perfume at 47.50

Input 3:
1 imported bottle of perfume at 27.99
1 bottle of perfume at 18.99
1 packet of headache pills at 9.75
1 box of imported chocolates at 11.25

OUTPUT

Output 1:
1 book : 12.49
1 music CD: 16.49
1 chocolate bar: 0.85
Sales Taxes: 1.50
Total: 29.83

Output 2:
1 imported box of chocolates: 10.50
1 imported bottle of perfume: 54.65
Sales Taxes: 7.65
Total: 65.15

Output 3:
1 imported bottle of perfume: 32.19
1 bottle of perfume: 20.89
1 packet of headache pills: 9.75
1 imported box of chocolates: 11.85
Sales Taxes: 6.70
Total: 74.68
==========

To solve this problem I used a composite to calculate taxes. The "TaxComposite" type allows you to bundle several different taxes all in one type. So when calculating taxes, the calculation with iterate through all the taxes and add the calculated tax and return the total value.

    public class TaxComposite : ITax {
        public TaxComposite( params ITax[] taxes ) : this( new List< ITax >( taxes ) ) {}

        public TaxComposite( IEnumerable< ITax > taxes ) {
            _taxes = new List< ITax >( taxes );
            _amount = CalculateAmount( );
            _type = CalculateType( );
        }

        public double Amount {
            get { return _amount; }
        }

        public TaxTypes Type {
            get { return _type; }
        }

        public IMoney CalculateTaxFor( IMoney price ) {
            return CalculateTaxFor( price, RoundingDelegateFactory.RoundToNearestTenCents );
        }

        public IMoney CalculateTaxFor( IMoney price, RoundingStrategy round ) {
            IMoney total = new Money( );
            Summary( delegate( ITax tax ) { total = total.Add( tax.CalculateTaxFor( price, round ) ); } );
            return total;
        }

        private double CalculateAmount( ) {
            double amount = 0d;
            Summary( delegate( ITax tax ) { amount += tax.Amount; } );
            return amount;
        }

        private TaxTypes CalculateType( ) {
            TaxTypes type = TaxTypes.None;
            Summary( delegate( ITax tax ) { type = type | tax.Type; } );
            return type;
        }

        private void Summary( Action< ITax > toDo ) {
            foreach ( ITax tax in _taxes ) {
                toDo( tax );
            }
        }

        private readonly IList< ITax > _taxes;
        private readonly double _amount;
        private readonly TaxTypes _type;
    }

"The Composite Pattern allows you to compose objects into tree structures to represent part-whole hierarchies. Composite lets clients treat individual objects and compositions of objects uniformly." - Head First Design Patterns

I used a TaxFactory type to construct the TaxComposite type which gathers all the taxes that match a specified predicate and injects it into the TaxComposite constructor. It looks like...

    public static class TaxFactory {
        public static ITax Create( TaxTypes forTaxes ) {
            return new TaxComposite(
                Taxes.FindBy( delegate( ITax tax ) { return ( tax.Type & forTaxes ) == tax.Type; } ) );
        }

The tax type is an enum that uses the flags attribute so that I can enable different bits for different taxes.

    [Flags]
    public enum TaxTypes {
        None = 0x00,
        Sales = 0x01,
        Import = 0x02
    }

Taxes is a static type that contains different types of taxes. The FindBy method allows for different strategies to be passed into to gather different types of taxes based on different critera. The above example returns all the taxes that are enabled in the "forTaxes" argument. FindBy is defined like...

        public static IEnumerable< ITax > FindBy( Predicate< ITax > condition ) {
            foreach ( ITax tax in taxes ) {
                if ( condition( tax ) ) {
                    yield return tax;
                }
            }
        }

I'm not sure if this is the most flexible design, but if i need to make changes to tax rates I can do that in one spot. The only catch is that it requires a re-compile to take a effect. In a full blown implementation I may want to consider using a "service" to retrieve the tax rates. Also, in this implementation in order to add new taxes I have to added it too 2 different locations. The first is the TaxTypes enum and the second is the Taxes static holder class. This leaves a bit of a smell...

Head First Design Patterns (Head First)
by Elisabeth Freeman, Eric Freeman, Bert Bates, Kathy Sierra

Read more about this title...

#

Design Principles

Sunday, September 09, 2007 4:12:54 PM (Mountain Standard Time, UTC-07:00)

The Open-Closed Principle (OCP): Classes should be open for extension, and closed for modification.

The Don't Repeat Yourself Principle (DRY): Avoid duplicate code by abstracting out things that are common and placing those things in a single location.

The Single Responsibility Principle (SRP): Every object in your system should have a single responsibility, and all the objects services should be focused carrying out that single responsibility.

The Liskov Substitution Principle (LSP): Subtypes must be substitutable for their base types. (The LSP is all about well-designed inheritance.)

The Hollywood Principle: Don't call us, we'll call you.

The Law of Demeter (The principle of least knowledge): Only talk to your immediate friends.

Delegation is when you hand over the responsibility for a particular task to another class or method.

Composition allows you to use behavior from a family of other classes, and to change that behavior at runtime.

Aggregation is when one class is used as part of another class, but still exists outside of that other class.

Encapsulate what varies.

Favor composition over inheritance.

Program to interfaces, not implementations.

Strive for loosely coupled designs between objects that interact.

Depend on abstractions. Do not depend on concrete classes.

Head First Object-Oriented Analysis and Design: A Brain Friendly Guide to OOA&D (Head First)
by Brett D. McLaughlin, Gary Pollice, Dave West

Read more about this title...

#

The Factory Pattern

Monday, September 03, 2007 2:42:39 PM (Mountain Standard Time, UTC-07:00)

To demo how the Factory Method and Abstract Factory patterns work I've put together an example in C#. For this example I've got 2 different Banks, CIBC, and Royal Bank. Each bank offers a chequing and savings account. Through the use of the Factory Method and Abstract Factory, the sample shows you how to create different types of bank accounts.

"The Factory Method Pattern defines an interface for creating an object, but lets subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses." - Head First Design Patterns

IBank has a single method called "GetAccountFactory()" that returns a IBankAccountFactory. This allows types that implement the interface to specify what type of bank account factory to construct and return.

    public interface IBank {
        string Name { get; }
        IBankAccountFactory GetAccountFactory( );
    }

So CIBC implementation of IBank will return a CIBCBankAccountFactory.

    public class CibcBank : Bank, IBank {
        public CibcBank( ) : base( "CIBC" ) {}

        public override IBankAccountFactory GetAccountFactory( ) {
            return new CibcBankAccountFactory( );
        }
    }

"The Abstract Factory Pattern provides an interface for creating families of related or dependent objects without specifying their concrete classes." - Head First Design Patterns

IBankAccountFactory is an abstract factory for creating different types of bank accounts. In my provided example you'll see that the IBankAccountFactory has two methods defined in it, both of which return an IBankAccount:

  • CreateChequingAccount()
  • CreateSavingsAccount()
    public interface IBankAccountFactory {
        IBankAccount CreateChequingAccount( );
        IBankAccount CreateSavingsAccount( );
    }

To create a CIBC chequing account, the client code might look something like this:

            IBank bank = new CibcBank( );
            IBankAccountFactory factory = bank.GetAccountFactory( );
            IBankAccount chequingAccount = factory.CreateChequingAccount( );

 

To create a Royal Bank chequing account, the client code might look something like this:

            IBank bank = new RoyalBank( );
            IBankAccountFactory factory = bank.GetAccountFactory( );
            IBankAccount chequingAccount = factory.CreateChequingAccount( );

 

Head First Design Patterns (Head First)
by Elisabeth Freeman, Eric Freeman, Bert Bates, Kathy Sierra

Read more about this title...

DesignPatterns.Factory.zip (9.16 KB)

#

The State Pattern

Sunday, August 26, 2007 2:35:59 PM (Mountain Standard Time, UTC-07:00)

"The State Pattern allows an object to alter its behavior when its internal state changes. The object will appear to change it's class." - Head First Design Pattern

Head First Design Patterns (Head First)
by Elisabeth Freeman, Eric Freeman, Bert Bates, Kathy Sierra

Read more about this title...

 

Let's say I've got a point of sale terminal used for processing financial transactions. Let's say that at any given time the terminal can be in 1 of 6 states. Those states are:

  • Idle State: During this state an idle message is displayed on the screen of the POS terminal.
  • Card Swiped State: The terminal enters this state when a card is swiped.
  • Amount Entered State: The terminal enters this state when the transaction amount is entered.
  • PIN Entered State: The terminal enters this state when the customer enters their PIN.
  • Processing Transaction State: The terminal enters this state when it connects to a financial processor to process the transaction.
  • Transaction Approved State: The terminal enters this state when the transaction has been process and has been approved.
  • Transaction Rejected State: The terminal enters this state when the transaction was processed but was rejected.

Let's pretend the following is the client code that will use the point of sale terminal to process transactions.

            IPosTerminal terminal = new PosTerminal( );
            terminal.SwipeCard( "6278080000008205" );
            terminal.EnterAmount( 99.99 );
            terminal.EnterPin( "8012" );
            terminal.ProcessTransaction( );
            terminal.PrintReceipt( );

When the PosTerminal is first constructed it is immediate put into an Idle State which displays an idle message to screen. The PosTerminal has a property of type IState that all the concrete state types implement.

As actions are performed against the PosTerminal, they are delegated to the current state.

        public void SwipeCard( string cardNumber ) {
            _currentState.SwipeCard( cardNumber );
        }

        public void EnterAmount( double amount ) {
            _currentState.EnterAmount( amount );
        }

        public void EnterPin( string pin ) {
            _currentState.EnterPin( pin );
        }

        public void AuthorizeTransaction( ) {
            _currentState.ProcessTransaction( );
        }

        public void PrintReceipt( ) {
            _currentState.PrintReceipt( );
        }

        public void ProcessTransaction( ) {
            _currentState.ProcessTransaction( );
        }
In this implementation I've made it the concrete state types responsibility to transition to the next state. For example the IdleState might look like:
        public void SwipeCard( string cardNumber ) {
            _terminal.Transaction = new PosTransaction( );
            _terminal.Transaction.Date = DateTime.Now;
            _terminal.Transaction.CardNumber = cardNumber;
            _terminal.CurrentState = new CardSwipedState( _terminal );
        }

        public void EnterAmount( double amount ) {
            Console.Out.WriteLine( "Please swipe a card first." );
        }

...

With the state pattern you can re-order states and alter the implementation of a state with out having to change the subject of the state.

DesignPatterns.State.zip (7.13 KB)

#

The Adapter Pattern

Sunday, August 26, 2007 1:39:14 PM (Mountain Standard Time, UTC-07:00)

"The Adapter Pattern converts the interface of a class into another interface the clients expect. Adapter lets classes work together that couldn't otherwise because of incompatible interfaces." - Head First Design Patterns

Head First Design Patterns (Head First)
by Elisabeth Freeman, Eric Freeman, Bert Bates, Kathy Sierra

Read more about this title...

If you're trying to build a presentation layer that is platform agnostic, you might turn to adapters for simple UI controls. For example in ASP.NET there is a drop down list control, and in Win Forms there is the Combo Box control.

A quick an easy adapter to the two controls might look like:

    public interface IDropDownListAdapter {
        void BindTo( IEnumerable< IDropDownListItem > pairs );
        IDropDownListItem SelectedItem { get; }
    }

Each drop down list item might look like:

    public interface IDropDownListItem {
        string Text { get; }
        string Value { get; }
    }

A concrete implementation for a Win Forms application might look like:

    public class DesktopDropDownList : IDropDownListAdapter {
        public DesktopDropDownList( ComboBox dropDown ) {
            _dropDown = dropDown;
            _pairs = new Dictionary< string, IDropDownListItem >( );
        }

        public void BindTo( IEnumerable< IDropDownListItem > pairs ) {
            if ( pairs != null ) {
                _pairs = new Dictionary< string, IDropDownListItem >( );

                foreach ( IDropDownListItem pair in pairs ) {
                    _dropDown.Items.Add( pair.Text );
                    _pairs.Add( pair.Text, pair );
                }
                _dropDown.SelectedIndex = 0;
            }
        }

        public IDropDownListItem SelectedItem {
            get { return !string.IsNullOrEmpty( _dropDown.Text ) ? _pairs[ _dropDown.Text ] : null; }
        }

        private ComboBox _dropDown;
        private IDictionary< string, IDropDownListItem > _pairs;
    }

A concrete implementation for a ASP.NET application might look like:

    public class WebDropDownList : IDropDownListAdapter {
        public WebDropDownList( DropDownList dropDown ) {
            _dropDown = dropDown;
        }

        public void BindTo( IEnumerable< IDropDownListItem > pairs ) {
            if ( pairs != null ) {
                foreach ( IDropDownListItem pair in pairs ) {
                    _dropDown.Items.Add( new ListItem( pair.Text, pair.Value ) );
                }
            }
        }

        public IDropDownListItem SelectedItem {
            get { return new DropDownListItem( _dropDown.SelectedItem.Text, _dropDown.SelectedItem.Value ); }
        }

        private DropDownList _dropDown;
    }

And voila... we can write a presentation layer that binds data to an IDropDownListAdapter, without having to be specific to WinForms, ASP.NET, WPF, Silverlight etc.

        public Presenter( IView view ) {
            _view = view;
        }

        public void Initialize( ) {
            IList< IDropDownListItem > items = new List< IDropDownListItem >( );
            items.Add( new DropDownListItem( "Yes", "1" ) );
            items.Add( new DropDownListItem( "No", "2" ) );
            _view.AreYouHappy.BindTo( items );
        }
DesignPatterns.Adapter.zip (4.56 KB)

#

The Observer Pattern

Friday, July 06, 2007 8:14:45 AM (Mountain Standard Time, UTC-07:00)

"The observer pattern defines a one-to-many dependency between objects so that when one object changes state, all of its dependents are notified and updated automatically." - Head First Design Patterns

What this means is that if you have objects that are interested in changes in another object, you allow the "observers" to register or subscribe to the subject. In the example provided, my wife and mother in law want to be notified whenever i look at cute girls. Each time i look at a cute girl they should be notified and then they can take whatever action they want.

Typically, you would push or pull the data from the subject (that's me), to the observers (that's my wife and her mom). Mo (that's me) contains an internal list of relatives that want to know what he's up to. Anytime one of his relatives wants to check in on him, the add themselves to Mo's interal list. If they're no longer interested, they can remove themselves for the internal list.

        public Mo( IList< IObserver > concernedRelatives ) {
            _concernedRelatives = concernedRelatives;
            LookAtCuteGirl += delegate { OnLookedAtCuteGirl( ); };
        }

        public event EventHandler LookAtCuteGirl;

        public void Add( IObserver observer ) {
            _concernedRelatives.Add( observer );
        }

        public void Remove( IObserver observer ) {
            _concernedRelatives.Remove( observer );
        }

        private IList< IObserver > _concernedRelatives;

        private void OnLookedAtCuteGirl( ) {
            foreach ( IObserver relative in _concernedRelatives ) {
                relative.Update( );
            }
        }

Let's say my wife is concerned and wants to check up on me, here's how she would do it.

        public MosWife( ISubject husband ) {
            _husband = husband;
            _husband.Add( this );
        }

        public void Update( ) {
            Console.Out.WriteLine( "Why is my husband looking at cute girls?" );
        }

        private ISubject _husband;

She's decided to always add her self to my internal list to see what I'm doing. If I should happen to check out a cute girl, she will be immediately notified. Lucky for me, my wife is pretty laid back, and asks herself "Why is my husband looking at cute girls?"...

Hopefully, this helps to demonstrate the observer pattern. I realize that it is rather contrived example, and the source could could be refactored. But hopefully it's clear.

For a better explanation, you should read...

Head First Design Patterns (Head First)
by Elisabeth Freeman, Eric Freeman, Bert Bates, Kathy Sierra

Read more about this title...

P.S. My wife does not check up on me, she's awesome!

DesignPatterns.Observer.zip (4.01 KB)

#

The Strategy Pattern

Monday, July 02, 2007 3:32:53 PM (Mountain Standard Time, UTC-07:00)

"The Strategy Pattern defines a family of algorithms, encapsulates each one, and makes them interchangeable. Strategy lets the algorithm vary independently from clients that use it." - Head First Design Patterns

This means that at runtime you can switch the algorithm being used by a particular object. In the example attached, there are a set of characters. Each characters has a weapon that they yield! At runtime, you can switch the type of weapon that a particular character is using.

For instance if the character king was constructed to use a default weapon, at runtime you could switch out the weapon that the king uses when he is fighting. This adheres to the open/closed principle, where the king object is open for extension but closed for modification.

In the future if we wanted to add new weapons, we can add them without having to change the implementation of the king object. This allows us to switch the type of weapon the king object is using at runtime!

            King king = new King( );
            king.Fight( );

            king.Weapon = new Axe( );
            king.Fight( );

            king.Weapon = new BowAndArrow( );
            king.Fight( );

 For more information check out...

Head First Design Patterns (Head First)
by Elisabeth Freeman, Eric Freeman, Bert Bates, Kathy Sierra

Read more about this title...

DesignPatterns.Strategy.zip (5.29 KB)

#