About Me

Training

Nothin But .Net Developer Bootcamp

Navigation

Search

Categories

On this page

Book Giveaway - Pragmatic Thinking & Learning + Pragmatic Programmer
Combining two disparate collections
Triggering events on UI components (WinForms)
Test examples with MBUnit and jpboodhoo.bdd
Source code moved to assembla
How I’m Currently Writing My BDD Style Tests – Part 2
How I’m Currently Writing My BDD Style Tests – Part 1
Excel Formatting with Visitors, Specifications, and Composites
Another Rhino Mocks extension method to support your AAA style
VS + ViEmu + (ReSharper modded with AutoHotkey)
BDD, AAA Style Testing and Rhino Mocks
Staying Humble
Small Update to BDD Macro
Solution Reorganizing (Again!!)
Got Icons?
Got A Spotter?
Score 1 For Eliminating your hands flight path
BDD Test Naming Macro - Speed Update
IMapper
BDD Specification Base Class
Nothin But .Net Store (Google Code) Breaking Change
MappingEnumerable
Getting started with BDD style Context/Specification base naming
Setting The Record Straight - My Thoughts On The MVP Variants (for web applications)
code.google.com/p/jpboodhoo!!!
Stop Reading - Start Doing
Huge Code Drop Coming!!!!!!!
The Static Gateway Pattern
Start Flying With ReSharper (and windows in general) - Use the Alt-Key
Drop the temporary lists and leverage yield
Screen Bound DTO Update (Getting the terminology right)
Screen Bound DTO's (Presentation Model)
Macro to aid BDD test naming style
Nothin But .Net - New York , NY ( October 22nd - 26th, 2007 )
Essential (almost) Language Agnostic Programming Books
The Bible's Take On Separation Of Responsibility
Read any good books lately?
Multithreading Question - One Solution
Learning Some New Stuff - Adapting And Filtering
The Open Closed Principle. - How Far Do You Take It
One Class To Rule Them All
Best Of Compendium!!

Archive

Blogroll

 Agile Developer Venkat's Blog
 Ayende @ Blog
 B#
 Barry Gervin's Software Architecture Perspectives
 Boy Meets World
 Brad Abrams
 Canadian Developers
 Christopher Steen
 Claritude Software News
 Clemens Vasters: Enterprise Development and Alien Abductions
 Coding Horror
 Coding in an Igloo
 Dare Obasanjo aka Carnage4Life
 Darrell Norton's Blog [MVP]
 David Hayden [MVP C#]
 Don Box's Spoutlet
 Eric Gunnerson's C# Compendium
 EZWeb guy: Jeffrey Palermo [C# MVP]
 Fear and Loathing
 Generalities & Details: Adventures in the High-tech Underbelly
 Greg Young [MVP]
 Greg's Cool [Insert Clever Name] of the Day
 IanG on Tap
 Ingo Rammer's Weblog
 ISerializable - Roy Osherove's Blog
 James Kovacs' Weblog
 Jason Haley
 Jean-Luc David
 Jeremy D. Miller -- The Shade Tree Developer
 JetBrains .NET Tools Blog
 Jimmy Nilsson's weblog
 John Bristowe's Weblog
 John Papa [MVP C#]
 Jon Skeet's Coding Blog
 JonGalloway.ToString()
 Jump the Fence or Walk Around
 Lambda the Ultimate - Programming Languages Weblog
 Larkware News
 Lutz Roeder
 Marquee de Sells: Chris's insight outlet
 Martin Fowler's Bliki
 Mike Nichols - SonOfNun Technology
 MSDN Magazine - .NET Matters
 MSDN Magazine - All Articles
 OdeToCode Blogs
 Onion Blog
 Planet TW
 Raymond Lewallen [MVP]
 Rockford Lhotka
 RodMan's Corner
 Roger Johansson's blog
 Sahil Malik - blah.winsmarts.com
 Sam Gentile's Blog
 Scott Bellware [MVP]
 Scott Hanselman's Computer Zen
 ScottGu's Blog
 secretGeek
 Service Station, by Aaron Skonnard
 Signum sine tinnitu--by Guy Kawasaki
 Stephen Toub
 Steve Eichert's Blog
 Steven Rockarts
 The Blog Ride
 The Coding Hillbilly
 The Daily WTF
 TheServerSide.net: News
 Tim Gifford
 Vance Morrison's Weblog
 you've been HAACKED

Disclaimer
The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.

RSS 2.0 | Atom 1.0 | CDF

Send mail to the author(s) E-mail

Total Posts: 519
This Year: 28
This Month: 0
This Week: 0
Comments: 1593

 Friday, June 25, 2010
Friday, June 25, 2010 8:04:06 AM (Mountain Standard Time, UTC-07:00) ( Programming | Training )
Have you been struggling with learning new concepts at work? Are you feeling overwhelmed by the constant flood of information that keeps coming at you from all angles? Do you constantly find yourself reading new books yet being unable to retain/apply any of the information that you have read. It might just be time to debug your brain!!

Pragmatic Thinking and Learning is one of those books that falls into my category of "Career Catalyst". These are books that when read and applied can have a lasting impact on how you go about executing your career. This book will help you identify your current style of learning, as well as give you techniques and exercises that you can use to identify and fix errors in your own thinking that may be preventing you from reaching your full potential when it comes to continuous
learning.

The Pragmatic Programmer is another one of those books that falls into the "Career Catalyst" category. In my opinion, any student entering a computer science/technology field should be provided this book as one of their first to read. If you can digest and apply the concepts outlined in this book it will provide you with a set of habits that will enable you to be a developer who charts a steady upward course with your career. I have spoken with lots of developers who have read this
book, and yet they have not taken the time to apply the concepts to their own career. If you have not read the book, or you are in the category of people who have read it but not really applied it, then there is no better time to start than today.

One of my goals when I am teaching is to encourage people to start thinking about how they can "chart their own course" and focus on finding a rhythm that enables them to learn new concepts in a JIT fashion, while also not becoming overwhelmed with the continual flood coming at them. I personally feel that the information contained in these two books can become instrumental in helping people figure out what it means for themselves to become more productive programmers.

If you have not read either one of both of these books, here is an opportunity. The first 5 people to email me will receive amazon credit (applicable to amazon.com) with which they can purchase a copy of both of these amazing books (you will have to take care of shipping costs).

Develop With Passion!!!

Comments [4] | | # 
 Monday, July 27, 2009
Monday, July 27, 2009 1:40:00 PM (Mountain Standard Time, UTC-07:00) ( C Sharp | Programming )

During class last week someone had written a piece of code right near the end of the last evening and I committed to showing them a potential refactoring that could be used. Here is the piece of code in question:

 

            var info_list = new List<ResolverConfigurationInfo>(parser());

            var resolver_items = info_list.Select(x => factory(x)).ToList();

 

            var index = 0;

            parser().each(item =>

            {

                resolvers.Add(item.AbstractType, resolver_items[index]);

                index++;

            });

The code is not really complicated. The messiness comes from the fact that an index needs to be maintained so that it can be used to lookup into another equally sized collection that is not the target of the iteration. There are obviously lots of ways to solve this, but I thought "why not just flatten the two collections into a single collection which eliminates the need for the index. Here is the resulting code that was produced:

 

            var info_list = new List<ResolverConfigurationInfo>(parser());

            var resolver_items = info_list.Select(x => factory(x)).ToList();

            info_list.union(resolver_items).each(item => resolvers.Add(item.first_value.AbstractType, item.second_value));

The union method is a new extension method that will take 2 disparate collections of the same size and combine them into a singular collection of Tuple<T,U> types. I created a simple Tuple class as nothing more than as an immutable parameter object. Here is the resulting code for it (very simple):

 

    public class Tuple<FirstType, SecondType>

    {

        public FirstType first_value { get; private set; }

        public SecondType second_value { get; private set; }

 

        public Tuple(FirstType first, SecondType second_type)

        {

            this.first_value = first;

            this.second_value = second_type;

        }

    }

Finally the code that pulls it all together is here in the extension method that does the heavy lifting:

 

        static public IEnumerable<Tuple<FirstType, SecondType>> union<FirstType, SecondType>(this IEnumerable<FirstType> first_set,

                                                                                             IEnumerable<SecondType> second_set)

        {

            Check.not_null(first_set,second_set);

            var first_list = first_set.ToList();

            var second_list = second_set.ToList();

            Check.ensure(first_list.Count == second_list.Count);

 

            for (var index = 0; index < first_list.Count; index++) yield return new Tuple<FirstType, SecondType>(first_list[index], second_list[index]);

        }

This method hides the details of the indexer into a utility method that can be used anywhere where 2 sets of disparate items of the same length need to be combined into a singular set.

Thoughts?

Develop With Passion!!

Comments [14] | | # 
 Tuesday, March 03, 2009
Tuesday, March 03, 2009 3:37:00 PM (Mountain Standard Time, UTC-07:00) ( .Net 3.0 | C Sharp | Programming )

I am currently working on a large winforms application (most likely the last winforms app before I make the transition to WPF). I am writing the application in a top down fashion, which means I drive out the tests for the presenters, and then move down through the corresponding layers to get a good vertical slice of functionality. When it comes to the development of the user interface I am using a command based UI to allow me to easily drive the testing of the screens easily from a unit test. One thing that I often need to do, is cause a UI component to trigger one of its own events to see if the command in question will be triggered. In order to allow for a bit of “guidance” I wrote a class that allows me to quickly trigger events on UI components. The following code snippet shows a usage:

EventTrigger.trigger_event<Events.ControlEvents>(x => x.OnKeyPress(new KeyPressEventArgs('A')), target);

I am making use of an expression tree to determine which event I want the target control to raise. This is easily done because most (almost all) UI components in both the .Net framework and 3rd party Winforms libraries follow a convention of having a method named “OnEventName” which is usually a protected method that the control itself can call when it wants to raise its event. The EventTrigger class lives in my test utilities and for my current application I have a set of Events classes which correspond to some of the third party, and raw .net, control I want to raise events on, here is a trimmed down section of one of the events class:

public class Events

{

    public interface ControlEvents : IEventTarget

    {

        void OnEnter(EventArgs args);

        void OnKeyPress(KeyPressEventArgs args);

    }

 

    public interface FormEvents : ControlEvents

    {

        void OnActivated(EventArgs e);

        void OnDeactivate(EventArgs e);

    }

}

Again, this class lives in my test utility folder and it contains interfaces specific to control types that I want to raise events on. For each control interface, I will place the events (as needed) that I need to be able to trigger from my unit tests. There are multiple ways to get the correct method signature on these interface methods, I can use the Object Browser, Reflector, or ReSharper can generate them!! The point is, the interface contains a public method that is the identical signature for a corresponding protected method on the target control. This is really to help get intellisense about the event I want to raise along with the arguments to the method itself. This works with all component frameworks as their EventArgs classes are always made public as to be able to be consumed by the components that will be hosting them.

Let’s get to the interesting part of this. I mentioned earlier that I am an expression tree to ultimately raise the event. Let's take a look at the trigger_event method signature to get a little understanding of what it is doing:

static public void trigger_event<Target>(Expression<Action<Target>> expression_representing_event_to_raise, object target) where Target : IEventTarget

Notice I am making use of the IEventTarget interface to basically simply constrain the incoming expression to be one based on one of the interfaces that lives in the “Events” class. The first argument “Expression<Action<Target>> is an expression representing the code. The target argument is the actual control to raise the event on. Here is the entire body of the trigger_event method:

static public void trigger_event<Target>(Expression<Action<Target>> expression_representing_event_to_raise, object target) where Target : IEventTarget

{

    var method_call_expression = expression_representing_event_to_raise.Body.downcast_to<MethodCallExpression>();

    var method_args = get_parameters_from(method_call_expression.Arguments);

    var method_name = method_call_expression.Method.Name;

    var method = target.GetType().GetMethod(method_name, binding_flags);

 

    Debug.Assert(target != null,"The target to raise the event on cannot be null");

    Debug.Assert(method != null,"There is no method called {0}, on a {1}".format_using(method_name,target.GetType().proper_name()));

 

    method.Invoke(target, method_args.ToArray());

}

This is test utility code, so I am able to make a lot of assumptions about how I am going to be consuming and using it. For starters I know that the ExpressionTree coming is is going to represent a MethodCallExpression. This post is only a small intro into the amazing concept of expression trees, if they are not something you are comfortable with, there is no time like the present to start playing around with them.

With a MethodCallExpression I have access to the MethodInfo object that contains information about the target method to call (this allows me to reflectively match upto the protected method on the target I want to raise the event on:

var method_name = method_call_expression.Method.Name;

var method = target.GetType().GetMethod(method_name, binding_flags);

Once I have the actual method to invoke, it still needs to be invoked with the correct arguments:

method.Invoke(target, method_args.ToArray());

The act of getting the arguments is the interesting part to this code (and a little gentle introduction to the world of ExpressionTrees for those of you who are not using them yet). The following line:

var method_args = get_parameters_from(method_call_expression.Arguments);

method_call_expression.Arguments is actually a collection of Expressions also. If you look back at the line of code that is using this the original trigger method, we’ll decompose it so that you can get a better idea of the expression tree created to represent the call to the event:

EventTrigger.trigger_event<Events.ControlEvents>(x => x.OnKeyPress(new KeyPressEventArgs('A')), target);

  • MethodCallExpression [x.OnKeyPress(
    • NewExpression[new KeyPressEventArgs(
      • ConstantExpression(‘A’)
    • )
  • )

Expression tree are “tree based structures. This simple line of code actually constructs an ExpressionTree that consists of a:

  • MethodCallExpression
    • NewExpression
      • ConstantExpression

Here is the complete code for the get_parameters_from method:

static IEnumerable<object> get_parameters_from(IEnumerable<Expression> parameter_expressions)

{

    foreach (var expression in parameter_expressions)

    {

        if (can_handle(expression)) yield return get_value_from_evaluating(expression);

        else cannot_handle(expression);

    }

}

This method iterates over each Expression in the incoming set and attempts to expand it to an actual object value. The can_handle method simply makes use of an existing dictionary that has been populated at startup with handlers that know how to evaluate the appropriate Expression:

static EventTrigger()

{

    expression_handlers = new Dictionary<ExpressionType, Func<Expression, object>>();

    expression_handlers[ExpressionType.New] = instantiate_value;

    expression_handlers[ExpressionType.MemberAccess] = get_value_from_member_access;

    expression_handlers[ExpressionType.Constant] = get_constant_value;

}

 

The get_value_from_evaluating(expression) method is very simple, it just look into the dictionary using the NodeType of the current expression, and invokes the expression handler against the expression so that it can be evaluated:

static object get_value_from_evaluating(Expression expression)

{

    return expression_handlers[expression.NodeType](expression);

}

Lets start by looking at the simplest one of them all, the method that evaluates a ConstantExpression:

static public object get_constant_value(Expression expression)

{

    return expression.downcast_to<ConstantExpression>().Value;

}

This method explicitly casts the incoming Expression to a ConstantExpression and then returns the expressions value. In our current example, that value will be the char ‘A’.

We’ll finish up by looking at the most involved one:

static object instantiate_value(Expression expression)

{

    var new_expression = expression.downcast_to<NewExpression>();

    var args = new_expression.Arguments.Select(constructor_argument_expression => get_value_from_evaluating(constructor_argument_expression));

    return new_expression.Constructor.Invoke(args.ToArray());

}

 

In the second line we are actually evaluating each of the constructor arguments expressions one at a time and having them also evaluated by the get_value_from_evaluating method. Because of the nested nature of expression trees, depending on the type of Expression that was passed in, this handles recursive traversal of the expression.

Once all of the arguments to the constructor have been evaluated, we can then invoke the expressions Constructor (which is a ConstructorInfo) to create the item. In our example here, it will cause the creation of a new KeyPressEventsArgs with the character of ‘A’ (the character was evaluated using the ConstantExpression we discussed earlier).

When it comes to testing a new control I can just create a new nested interface in my Events class, add public versions of the protected methods that I want to invoke (along with the correct arguments) and then I’m off to the races!!

Develop With Passion

Comments [1] | | # 
 Tuesday, January 27, 2009
Tuesday, January 27, 2009 6:08:00 AM (Mountain Standard Time, UTC-07:00) ( C Sharp | Programming )

The other day I placed a library up on assembla that I use as a place to store my current set of conventions on writing unit tests. My current flavour of testing focuses on the use of BDD to emphasize context and behaviour of a particular SUT (System under test) that I am exercising.

This post is not about detailing my current thinking on BDD, more to demonstrate some ways that you can use the very small framework in conjunction with MBUnit to remove a lot of cruft from your tests. To that end, the following are some sample tests written to demonstrate different aspects of the library:

1) Adding two numbers (without a because block):

 

    public class when_adding_2_numbers_together : observations_for_a_static_sut

    {

        [Observation]

        public void should_result_in_the_sum_of_the_2_numbers()

        {

            (2 + 2).should_be_equal_to(4);

        }

    }

Notice that the class simply inherits from a class named  observations_for_a_static_sut. This is the base class you will use when you are either testing a static class, or (as in this case) you are simply writing a quick inline test.

2) Adding two numbers with a because block (the because block is meant to focus your eyes to the actual behaviour you are exercising:

    public class when_adding_2_numbers_together : observations_for_a_static_sut

    {

        static int result;

 

        because b = () =>

        {

            result = 2 + 2;

        };

 

        [Observation]

        public void should_result_in_the_sum_of_the_2_numbers()

        {

            result.should_be_equal_to(4);

        }

    }

The behaviour being exercises is placed inside of a anonymous method block assigned to a delegate type (because). It is also important to note that the field is static.

Let’s look at a slightly more involved test that has some dependencies, a factory method for the system under test, etc.  Here is the start:

 

        [Concern(typeof (DatabaseGateway))]

        public class when_retrieving_a_set_of_rows_based_on_a_query : observations_for_a_sut_without_a_contract<DatabaseGateway>

        {

            static IEnumerable<DataRow> result;

            static IQuery query;

            static IDatabaseConnectionFactory connection_factory;

            static IDatabaseConnection connection;

            static IDbCommand command;

            static IDataReader reader;

 

            context c = () =>

            {

                connection_factory = an<IDatabaseConnectionFactory>();

                query = an<IQuery>();

                connection = an<IDatabaseConnection>();

                command = an<IDbCommand>();

                reader = an<IDataReader>();

 

                connection_factory.Stub(x => x.create()).Return(connection);

                connection.Stub(x => x.create_to_run(query)).Return(command);

                command.Stub(x => x.ExecuteReader()).Return(reader);

            };

 

            because b = () =>

            {

                result = sut.get_rows_matching(query);

                result.force_traversal();

            };

 

            [Observation]

            public void should_leverage_db_infrastructure_to_return_a_set_of_rows_from_the_db()

            {

                result.should_not_be_null();

            }

 

            [Observation]

            public void should_dispose_the_appropriate_items()

            {

                connection.was_told_to(x => x.Dispose());

            }

 

            public override DatabaseGateway create_sut()

            {

                return new DatabaseGateway(connection_factory);

            }

        }

Let’s start by taking a look at the context block:

            context c = () =>

            {

                connection_factory = an<IDatabaseConnectionFactory>();

                query = an<IQuery>();

                connection = an<IDatabaseConnection>();

                command = an<IDbCommand>();

                reader = an<IDataReader>();

 

                connection_factory.Stub(x => x.create()).Return(connection);

                connection.Stub(x => x.create_to_run(query)).Return(command);

                command.Stub(x => x.ExecuteReader()).Return(reader);

            };

In this block I define all of the dependencies that are going to come into play during the test. The “an” method, is a generic method that lives on the base class, which basically creates a mock of the contract in question. It carries on to setup return values for method calls that will be leveraged during the course of the SUT doing its work. Unfortunately, it is hard to identify which mocks are direct dependencies of the sut and which are collaborators. It is only when you look at the factory method for the system under test:

            public override DatabaseGateway create_sut()

            {

                return new DatabaseGateway(connection_factory);

            }

Here it is evident that the direct dependency of the DatabaseGateway is the connection_factory (IDatabaseConnectionFactory). The because block highlights the behaviour being tested:

            because b = () =>

            {

                result = sut.get_rows_matching(query);

                result.force_traversal();

            };

The force_traversal method is a utility method that forces the traversal of an enumerable. It is necessary as the implementation of the method under test uses deferred execution by nature of leveraging the yield keyword and returning an IEnumerable. Here is the implementation of the class under test:

        public class DatabaseGateway

        {

            IDatabaseConnectionFactory connection_factory;

 

            public DatabaseGateway(IDatabaseConnectionFactory connection_factory)

            {

                this.connection_factory = connection_factory;

            }

 

            public IEnumerable<DataRow> get_rows_matching(IQuery query)

            {

                var table = new DataTable();

                using (var connection = connection_factory.create())

                using (var command = connection.create_to_run(query))

                using (var reader = command.ExecuteReader())

                {

                    table.Load(reader);

                }

                foreach (DataRow row in table.Rows) yield return row;

            }

        }

Let’s now show the exact same test written with the minimum amount of plumbing code that is necessary:

        [Concern(typeof (DatabaseGateway))]

        public class when_retrieving_a_set_of_rows_based_on_a_query : observations_for_a_sut_without_a_contract<DatabaseGateway>

        {

            static IEnumerable<DataRow> result;

 

            context c = () =>

            {

                the_dependency<IDatabaseConnectionFactory>().Stub(x => x.create()).Return(the_dependency<IDatabaseConnection>());

                the_dependency<IDatabaseConnection>().Stub(x => x.create_to_run(the_dependency<IQuery>())).Return(the_dependency<IDbCommand>());

                the_dependency<IDbCommand>().Stub(x => x.ExecuteReader()).Return(the_dependency<IDataReader>());

            };

 

            because b = () =>

            {

                result = sut.get_rows_matching(the_dependency<IQuery>());

                result.force_traversal();

            };

 

            [Observation]

            public void should_leverage_db_infrastructure_to_return_a_set_of_rows_from_the_db()

            {

                result.should_not_be_null();

            }

 

            [Observation]

            public void should_dispose_the_appropriate_items()

            {

                the_dependency<IDatabaseConnection>().was_told_to(x => x.Dispose());

            }

        }

The factory method has been removed along with the fields to reference the dependencies that come into play. For readability, I think this approach loses out, so this last way is the way I would finish up with:

        [Concern(typeof (DatabaseGateway))]

        public class when_retrieving_a_set_of_rows_based_on_a_query : observations_for_a_sut_without_a_contract<DatabaseGateway>

        {

            static IEnumerable<DataRow> result;

            static IQuery query;

            static IDatabaseConnectionFactory connection_factory;

            static IDatabaseConnection connection;

            static IDbCommand command;

            static IDataReader reader;

 

            context c = () =>

            {

                connection_factory = the_dependency<IDatabaseConnectionFactory>();

                query = an<IQuery>();

                connection = an<IDatabaseConnection>();

                command = an<IDbCommand>();

                reader = an<IDataReader>();

 

                connection_factory.Stub(x => x.create()).Return(connection);

                connection.Stub(x => x.create_to_run(query)).Return(command);

                command.Stub(x => x.ExecuteReader()).Return(reader);

            };

 

            because b = () =>

            {

                result = sut.get_rows_matching(query);

                result.force_traversal();

            };

 

            [Observation]

            public void should_leverage_db_infrastructure_to_return_a_set_of_rows_from_the_db()

            {

                result.should_not_be_null();

            }

 

            [Observation]

            public void should_dispose_the_appropriate_items()

            {

                connection.was_told_to(x => x.Dispose());

            }

        }

This tests reintroduces the fields to store the mocks. It still removes the factory method, and it uses the following two different methods:

  • the_dependency<T>
  • an<T>

to differentiate between a constructor depedency and a mock that happens to come into play while collaborating with that dependency.

There are lots of other things you can do, and I will post more examples as requests come in!!

 

Develop With Passion!!

Comments [5] | | # 
 Thursday, January 22, 2009
Thursday, January 22, 2009 1:36:00 PM (Mountain Standard Time, UTC-07:00) ( Programming )

A couple of people have asked about where the source code I placed on google code had moved. It has all been moved over to assembla. Here are the projects that are currently up there:

bdddoc - http://svn2.assembla.com/svn/bdddoc – Tool for generating html documents based on your unit tests. Works with any attribute driven testing framework.


jpboodhoo.bdd - http://subversion.assembla.com/svn/jpboodhoo_bdd – Library that contains my current approach to writing tests. Is basically a thin wrapper on top of MBUnit 2 that has a much more natural feel to it. If you want some examples of how to write tests with this, please send email requests for a blog post!!


nbdn_web_store - http://svn2.assembla.com/svn/nbdn_web_store – Web store project that was harvested from the 2008 Germany Nothin But .Net course. Demonstrates the use of front controller architecture, fluent interfaces, bdd, interface based programming etc…

Develop With Passion!!

Comments [3] | | # 
 Monday, December 22, 2008
Monday, December 22, 2008 2:29:00 PM (Mountain Standard Time, UTC-07:00) ( C Sharp | Programming )

We left off in part 1 with an example of a test written using my current style and I finished off outlining the skeleton for one of the base classes that shields the actual Concern classes from a lot of noisy test related nomenclature.

In this post I am going to break down the responsibilities of the “an_observations_basic_set_of_behaviours” class. For a quick reminder, here is the skeleton outline of the class:

        [Observations]

        public abstract class an_observations_set_of_basic_behaviours

        {

            static protected IDictionary<Type, object> dependencies;

            static Exception exception_thrown_while_the_sut_performed_its_work;

            static protected Action behaviour_of_the_sut;

 

            [SetUp]

            public void setup() {}

 

            void prepare_to_make_an_observation() {}

 

            [TearDown]

            public void tear_down() {}

 

            after_all_observations a = () => dependencies.Clear();

 

            ICommand build_command_chain<DelegateType>() {}

 

            void run_action<DelegateType>() {}

 

            protected virtual void initialize_the_sut() {}

 

            static public void doing(Action action) {}

 

            static protected Exception exception_thrown_by_the_sut

            {

                get { }

            }

 

            static Exception get_exception_throw_by(Action action) {}

 

            static protected object an(Type type) {}

 

            static protected InterfaceType an<InterfaceType>() where InterfaceType : class {}

        }

    }

Let’s start off by discussing the fields:

static protected IDictionary<Type, object> dependencies;

 

  • This field is hopefully pretty self explanatory. It is a dictionary that will contain any direct dependencies of the SUT. In most of my apps I tend to favour Constructor based DI so, this dictionary basically contains the set of objects (mocks and/or reals) that the sut will depend on. How this gets populated will be discussed later.

static Exception exception_thrown_while_the_sut_performed_its_work;

  • This field will be used to store a reference to the exception that the sut threw while it performed its work. Is used in conjunction with the doing() method (more on that later).

static protected Action behaviour_of_the_sut;

  • I am going to revisit this field when we discuss the doing() method

That takes care of the first set of fields, lets move on to a method that should look very familiar to MbUnit/NUnit people:

        [SetUp]

        public void setup()

        {

            exception_thrown_while_the_sut_performed_its_work = null;

            dependencies = new Dictionary<Type, object>();

            prepare_to_make_an_observation();

        }

This is a traditional MbUnit setup method. Because it is decorated with the SetUp attribute, all of the code in this method will get run once before each observation (test). Essentially this method is used to reset stateful fields, this is not that interesting. The guts of setup happen in the following method:

        void prepare_to_make_an_observationjjj()

        {

            run_action<context>();

            initialize_the_sut();

            run_action<after_the_sut_has_been_initialized>();

            run_action<because>();

        }

In this base class the initialize_the_sut method has an empty implementation. The prepare_to_make_an_observation method leverages a hook method (initialize_the_sut) that can be leveraged (it will be by an_observation_for_an_instance_sut). In the base class, it is a virtual method with no implementation. As you can see, this method is responsibility for performing the following actions before an observation can be made:

  • Establishing the context (run_action<context>())
  • Initializing the SUT
  • Invoking the behaviour under test (run_action<because>())

Again this is a small little method that basically serves as a driver for prepping the way to be able to make observations. By the time we actually enter an observation in our actual fixtures, the SUT has already performed its work!!

Now I am sure you are wondering what the deal is with the run_action method? Here is the signature for the run_action method:

void run_action<DelegateType>()

This method is a generic method that accepts a delegate type as its generic argument. Again this is a convention that is understood by the naming of the generic parameter. You can’t place constraints on a generic method that constrain the Generic argument to be assignable from a delegate (of course, you can do this with a guard clause). Here are the different delegate signatures that I defined for use in the test-harnesses:

public delegate void context();

public delegate void after_the_sut_has_been_initialized();

public delegate void because();

public delegate void after_each_observation();

You may be wondering why I did not just use the plain old action delegate as opposed to creating discrete delegate types. This is so the driver class (this one we are examining) has a clearer way of differentiation between the different delegates. Without the named delegate types, I would have to resort to following a convention for the name I assigned to a field for an Action delegate (messy, messy).

Here is the full implementation of the run_action method:

        void run_action<DelegateType>()

        {

            build_command_chain<DelegateType>().run();

        }

 

Once again, this method is pretty simple as it is really delegating its responsibility to whatever gets created by the build_command_chain method. So lets dive into the full body of this method, as this is really where the majority of the work is being done:

        ICommand build_command_chain<DelegateType>()

        {

            var actions = new Stack<ICommand>();

            var current_class = GetType();

 

            while (current_class.is_a_concern_type())

            {

                actions.Push(new DelegateFieldInvocation(typeof (DelegateType), this, current_class));

                current_class = current_class.BaseType;

            }

 

            return actions.as_command_chain();

        }

So what is going on here. Take a look at this test one more time as it will give you a good visual as to what is going on:

    [Concern(typeof (MappingStep<,,>))]

    public class when_an_expression_mapping_step_is_told_to_run :

        concern_for_mapping_step

 

    {

        static SomeSourceObject item;

        static SomeDestinationObject destination;

        static string name;

 

        context c = () =>

        {

            item = new SomeSourceObject();

            name = "JP";

            destination = new SomeDestinationObject();

 

            source_evaluator.Stub(x => x.evaluate_against(item)).Return(name);

        };

 

        because b = () => sut.map(item, destination);

 

        [Observation]

        public void should_run_the_target_evaluator_passing_it_the_information_retrieved_from_evaluating_the_source()

        {

            target_action.was_told_to(x => x.act_against(destination, name));

        }

    }

I chose not to also put in this Concerns base class, the only important thing to remember about the “concern_for_mapping_step” is that it also has its own context block :

         context c = () =>

        {

            target_action = the_dependency<ITargetAction<SomeDestinationObject, string>>();

            source_evaluator = the_dependency<ISourceEvaluator<SomeSourceObject, string>>();

        };

 

It is important to remember that the “an_observations_basic_set_of_behaviours” class is the test driver. Here is the inheritance hierarchy for this current test fixture:

  • an_observations_basic_set_of_behaviours
    • observations_for_an_instance_sut
      • obsevations_for_a_sut_with_a_contract
        • concern_for_mapping_step
          • when_an_expression_mapping_step_is_told_to_run

At any point in the chain (starting from the top, working down) each level could have its own context to run. The run_action method is responsible for walking the inheritance hierarchy of a particular concern and building a chain of “commands” for a particular delegate type. Once the command chain has been build, the chain can be executed in the right order (from top to bottom) to ensure that any prior context in a base class has been established before a subclass runs. If you are already thinking, could he not have done the same thing with abstract/virtual methods. Yes. When I initially started down that route, I kept getting stung by forgetting to call back into the base method. By now having to worry about calling the base method prior to doing your own work, you as a developer can just focus on the context that is applicable to a particular test. You can do this, as the driver class is responsible for ensuring blocks run in the order they are supposed to run. Without the driver class, all the fields that have lambdas assigned to them would be useless as they are just sitting there waiting to be invoked.

At the end of the while loop in the build_command_chain method there will be a stack (I chose stack as it is a LIFO structure, which is perfect for walking a class hierarchy, as when the last item is added – the base class, I can just start popping items off and they will be in the right order, ending with the ultimate test class itself). The stack itself is being used to store a set of ICommand implementations. Here is the ICommand interface:

    public interface ICommand

    {

        void run();

    }

This is a pretty stock interface that I have used for years. The uses are endless!! How does the loop know when to end? What is with the following method?:

current_class.is_a_concern_type()

The field current_class is of type Type. The is_a_concern_type method is a local extension method that has the following implementation:

    static public bool is_a_concern_type(this Type type)

    {

        return typeof (an_observations_set_of_basic_behaviours)

            .IsAssignableFrom(type);

    }

This method just adds a bit of readability (from the point of usage, which is a huge bonus of extension methods) and ensures that we wont worry about putting anything that is not either a derivative of an_observations_set_of_basic_behaviours or the an_observations_set_of_basic_behaviours type itself on the stack (it will always be the top item on the stack at the end of the traversal).

So lets explore the line that does the grunt work:

actions.Push(new DelegateFieldInvocation(typeof (DelegateType), this, current_class));

Keep in mind that the actions field is a stack of ICommand. It stands to reason that the DelegateFieldInvocation class is an ICommand implementation. Which it is. The DelegateFieldInvocation class takes in its constuctor a delegate type to scour for, an instance to act against (always this), and finally the particular type to reflect against (this will change as we continue to walk up the inheritance hierarchy). Here is the implementation of the DelegateFieldInvocation:

    public class DelegateFieldInvocation : ICommand

    {

        const BindingFlags probing_flags = BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.DeclaredOnly;

        Type delegate_type;

        readonly object instance;

        IEnumerable<FieldInfo> fields;

 

        public DelegateFieldInvocation(Type delegate_type, object instance, Type current_type)

        {

            fields = current_type.GetFields(probing_flags);

            this.delegate_type = delegate_type;

            this.instance = instance;

        }

 

        public void run()

        {

            all_fields_of_the_target_delegate_type().each(x => x.GetValue(instance).downcast_to<Delegate>().DynamicInvoke());

        }

 

        IEnumerable<FieldInfo> all_fields_of_the_target_delegate_type()

        {

            return fields.Where(x => x.FieldType.Equals(delegate_type));

        }

    }

All this command does in its run implementation is scour all of the fields in the “current_type” and filters them to look for only fields of the certain delegate type being searched for. Once the particular delegate type is found, we get the value of the field using the instance:

x.GetValue(instance).downcast_to<Delegate>()

downcast_to is just a utility extension method to do casting. At this point we have an actual reference to the delegate. With that, because we know (again by convention) that all of the delegate types we are working with are void with no arguments, they can just be invoked by using the DynamicInvoke method that lives on the delegate class. Again, the beauty of the command pattern allows this command to be queued up with all the information that it needs, and then it can simply perform it when it is told to run.

Of course, the build_command_chain ends with this line:

return actions.as_command_chain();

All that this method does is return a Composite of commands that when told to run, will run each of the commands that it is composed with (we’ll dive into that at a later date). So back up in the run_action method:

build_command_chain<DelegateType>().run();

It should now be clear to see that the run() method is invoked on the Composite, that will cause all of the commands to run in sequence. In the case of run_action<context> it will cause a Composite command to be built that is composed of commands to run “context” delegates from the Grandparent down to the actual Concern itself.

For clarification, look again at how the run_action method is used:

        void prepare_to_make_an_observation()

        {

            run_action<context>();

            initialize_the_sut();

            run_action<after_the_sut_has_been_initialized>();

            run_action<because>();

        }

The other calls to run action simply walk down the hierarchy invoking the appropriate delegate fields that may or may not be present in the actual test classes. The because block is the behaviour we are invoking of our system under test. In the case of the test we first examined:

because b = () => sut.map(item, destination);

For the design pattern aware, you will have already realized that the prepare_to_make_an_observation method (along with the use of delegate fields that can be defined at any level of the hierarchy) is just a specialization of the template method pattern, the main difference being that subclasses do not provide their behaviour by overriding abstract methods, rather they just simply have to define fields of a certain delegate type, that contain the code that will be invoked dynamically by the base class using reflection!!

That is enough for now, we’ll carry on the drilldown in the next part!!

Develop With Passion!!

Comments [4] | | # 
 Thursday, December 18, 2008
Thursday, December 18, 2008 3:08:00 PM (Mountain Standard Time, UTC-07:00) ( C Sharp | Programming )

In the ongoing goal of “Competing against yourself daily” I have changed many things about my coding style over this past year. One of the areas that has been most affected by all of this is how I organize and write tests for the systems I am building.

Here is an example of a test that I wrote for something called a MappingStep:

public abstract class concern_for_mapping_step : observations_for_a_sut_with_a_contract<IMappingStep<SomeSourceObject, SomeDestinationObject>, MappingStep<SomeSourceObject, SomeDestinationObject, string>> { static protected ITargetAction<SomeDestinationObject, string> target_action; static protected ISourceEvaluator<SomeSourceObject, string> source_evaluator; context c = () => { target_action = the_dependency<ITargetAction<SomeDestinationObject, string>>(); source_evaluator = the_dependency<ISourceEvaluator<SomeSourceObject, string>>(); }; } [Concern(typeof (MappingStep<,,>))] public class when_an_expression_mapping_step_is_told_to_run : concern_for_mapping_step { static SomeSourceObject item; static SomeDestinationObject destination; static string name; context c = () => { item = new SomeSourceObject(); name = "JP"; destination = new SomeDestinationObject(); source_evaluator.Stub(x => x.evaluate_against(item)).Return(name); }; because b = () => sut.map(item, destination); [Observation] public void should_run_the_target_evaluator_passing_it_the_information_retrieved_from_evaluating_the_source() { target_action.was_told_to(x => x.act_against(destination, name)); } }

First thing to notice is a convention I have started using when it comes to writing tests. I create a base class named concern_for_[name_of_system_under_test]. You will also see that all of the fields in the test classes are static and not instance. The 2 fields in the base concern_for_mapping_step class are there to hold references to dependencies of the system under test. I don’t need to have them there as they are accessible using a helper method on the base test class (more about the base test class hierarchy in a minute), I just like to have them as I find it a bit more readable than calling methods to access the dependencies of the system under test ex:

  • I prefer referring to a field named: target_action as opposed to repeatedly having to call a method such as:
    • Mock<ITargetAction<SomeDestinationObject,string>> / the_dependency<ITargetAction<SomeDestinationObject,string>> (of course, in this example, the generic signatures emphasize the issue even more!!!)

Second thing to notice is the use of a field named c which is of a delegate type named context. Here is the definition for the context delegate type:

public delegate void context();

Nothing all that special about it. This field will get used back up in the base test class to “establish the context for the test to run” much like a traditional setup method would / constructor if you are using xUnit.

If we focus our attention now on the “when_an_expression_mapping_step_is_told_to_run’ class, you will see that it inherits from the base concern class. The base concern class will be used to hide fields/extra noise that would otherwise pollute the test. You will see that this test also has its own context block. Context blocks are applied recursively from the top of the hierarchy down, this ensures that any contexts in base classes will always run first. In the past I would use overriden methods to accomplish this, but then you had to deal with making sure to call the base “establish_context” method, and if you forgot you could have tests fail because of a silly omission. By adhering to a convention of placing scaffolding in a context block, the “framework” takes care of ensuring that contexts are run in the correct order.

The following block:

because b = () => sut.map(item, destination);

focuses our attention to what behaviour of the system under test we are testing (in the particular context). You will notice that I use the name of the class to embody both action and context. Of course, in this particular test I am focusing on a happy day scenario. An example of testing in another context could be a test fixture named:

  • when_a_mapping_step_is_told_to_map_from_an_invalid_source

This name implies context. In the first test I am just testing the behaviour of mapping. In the second test (which is a different context), I am testing how the sut behaves when it is provided invalid data. One of the things that is hard to see from this example is that one context (test fixture) could have several observations (assertions). In this current example there is only 1 observation being made.

Notice that the because block, like the context block is a field of a simple delegate type (another void delegate type). This means that the code does not execute as it is just an anonymous method of certain delegate type being assigned to a field of a matching delegate type.

Finally observations are made. Notice the use of the Observation attribute. Inside an observation (Test) I will make logical assertions against either the system under test, the dependencies, or the outputs of the method under test. It is best to try to stick to one logical assertion (keeping in mind that 2 actual assertions can be part of 1 logical assertion) per observation. This is why you will often see a single Context (TestFixture) with multiple Observations.

One of the things that you may have missed is the fact that the System Under Test is never instantiated. This is also taken care of in a base class. I have the ability to override the creation of the system under test, but for most tests, letting the SUT be created for me saves a couple of lines of code, and allows me to not have to change things as more dependencies get added.

So how does all of this work? Currently all of this is coded to run against MBUnit 2.5. I have a project called jpboodhoo.commons.bdd (part of jpboodhoo.commons) where I place all of the plumbing code to make all of this work. Here is a snapshot of the project:

image

This is one of those utility type projects that got harvested over time as I saw patterns start to emerge. Under the concern folder there are 4 main classes:

image

In my projects I derive from either one of the following 3:

  • observations_for_a_static_sut
  • observations_for_a_sut_with_a_contract
  • observations_for_a_sut_without_a_contract

Those 3 base classes cover the range of classes I may want to write tests against. I am hoping that the naming of the classes is pretty self explanatory. Here are the definitions for each of the above 3 classes:

public abstract class observations_for_a_static_sut : an_observations_set_of_basic_behaviours { }

This one is the most basic, it simply inherits from “an_observations_set_of_basic_behaviours”. I derive from this class when I am testing static classes. The other 2 are equally as simple with a little twist:

public abstract class observations_for_a_sut_with_a_contract<Contract, ClassUnderTest> : observations_for_an_instance_sut<Contract, ClassUnderTest> where ClassUnderTest : Contract { }

I derive from this class when I want to write tests against a class, but code the tests against an interface of the class, and not the class itself. Here the term interface/contract applies to either a C# interface, or a class that the ClassUnderTest inherits from (usually an abstract class). The final base class (that I can choose to derive from) is very similar:

public abstract class observations_for_a_sut_without_a_contract<SystemUnderTest> : observations_for_an_instance_sut<SystemUnderTest, SystemUnderTest> { }

Notice how this class derives from the same class as the previous class, except that it uses the same type for providing the generic arguments to the “observations_for_an_instance_sut”

Again, the 3 classes that I have just covered are there to introduce a convention for people (right now just me) to follow when they are writing their own tests classes. The naming of the 3 makes it pretty simple( I think) to figure out which one you would start with.

With those 3 covered it really leaves the 2 “big ones” that hide a lot of plumbing and MBUnit specific details. Let’s start by taking a look at the skeleton for the “an_observations_set_of_basic_behaviours”:

[Observations] public abstract class an_observations_set_of_basic_behaviours { static protected IDictionary<Type, object> dependencies; static Exception exception_thrown_while_sut_performed_its_work; static protected Action behaviour_of_the_sut; [SetUp] public void setup() { } [TearDown] public void tear_down() { } void do_setup() { } after_each_observation a = () => dependencies.Clear(); ICommand build_command_chain<DelegateType>() { } void run_action<DelegateType>() { } protected virtual void initialize_system_under_test() { } static public void doing(Action action) { } static protected Exception exception_thrown_by_the_sut { } static Exception get_exception_throw_by(Action action_that_should_be_taken_by_the_sut) { } static protected object an(Type type) { } static protected InterfaceType an<InterfaceType>() where InterfaceType : class { } }

This is just the interface (we’ll dive into implementation of each method in time!!). Let’s break it down step by step. First thing you should see is the use of the Observations attribute on the class itself. This is basically just an alternative to the TestFixtureAttribute (thanks go to Albert Weinert for suggesting this). Here is the code:

[AttributeUsage(AttributeTargets.Class, AllowMultiple = false)] public class ObservationsAttribute : TestFixturePatternAttribute { public ObservationsAttribute(string description) : base(description) { } public ObservationsAttribute() { } public override IRun GetRun() { var run = new SequenceRun(); run.Runs.Add(new OptionalMethodRun(typeof (SetUpAttribute), false)); run.Runs.Add(new MethodRun(typeof (ObservationAttribute), true, true)); run.Runs.Add(new OptionalMethodRun(typeof (TearDownAttribute), false)); return run; } }

The main thing you should get out of this is that the GetRun method tells MbUnit to look for methods that are decorated with the ObservationAttribute, and to treat them as tests. The ObservationAttribute is really simple:

[AttributeUsage(AttributeTargets.Method, AllowMultiple = false)] public class ObservationAttribute : TestPatternAttribute { }

You have already seen this attribute used on the test earlier. The thing that should be immediately apparent about the “an_observations_basic_set_of_behaviours” class is that it is there to shield the rest of the test code from the details of whatever xUnit framework you are targeting (in this case, MBUnit).

Tomorrow I’ll continue by breaking down the responsibilities of this class in a piece meal fashion.

Develop With Passion!!

Comments [5] | | # 
 Wednesday, December 10, 2008
Wednesday, December 10, 2008 4:44:00 PM (Mountain Standard Time, UTC-07:00) ( C Sharp | Programming )

The title is definitely a mouthful!!

A project a year ago (yep, I’m quite behind on the technical blogging front) required the need for Excel generation and formatting. Unlike other Excel generation tasks I had done in the past, this particular task called for generation of tabbed workbooks, with graphs, fancy formatting etc. Much more involved than the trivial stuff I had typically done with excel in the past.

Applying formatting to elements in a tree is a perfect job for the Visitor pattern!! Of course, different types of formatting need to be applied to different cells, some cells need multiple types of formatting applied to them. Composite pattern can come to the rescue here. How can we filter out different types of formatting to certain cells / range of cells? The Specification pattern can come in handy here.

The project resulted in the creation of a fairly flexible excel formatting engine (that has been run against 3rd party excel frameworks SpreadSheetGear, and OfficeWriter).

Here is the interface for a cell visitor:

public interface ICellVisitor { void visit(IRange cell); }

And here is the implementation for the composite visitor:

public class CompositeCellVisitor : ICellVisitor { private IList<ICellVisitor> all_visitors; public CompositeCellVisitor() { all_visitors = new List<ICellVisitor>(); } public void add(ICellVisitor visitor) { all_visitors.Add(visitor); } public void add_all(IEnumerable<ICellVisitor> visitors) { foreach (var visitor in visitors) add(visitor); } public void visit(IRange cell) { foreach (var visitor in all_visitors) visitor.visit(cell); } }

As you can see, a composite basically implements the same interface as the things it is being composed of and it simply (for the most part) does its job by delegating to each of its leaf items to do their jobs. In this case, each visitor is told to visit a cell. This means that when an iterator for a spreadsheet (which essentially makes sure to walk over each cell in the spreadsheet) walks to a certain cell, it can then tell the CompositeVisitor to visit the cell. Because the composite is composed of all the possible visitors that can visit a cell, you only need to pass through the spreadsheet once to apply all formatting.

Here are the names of some of the formatting that can be done:

  • ApplyAllCellBorders
  • AutoFitCellWidth
  • BoldFont
  • ChangeFontSize
  • CustomFormat
  • FormatBackColor

Here is the implementation of one of the visitors:

public class FormatBackColor : ICellVisitor { private Color color; public FormatBackColor(Color color) { this.color = color; } public void visit(IRange cell) { cell.Interior.Color = color; } }

As you see, the visitor is only responsible for a single discrete action. It has no knowledge as to whether or not it should actually apply itself against a cell, it just goes ahead and applies itself. This would obviously cause problems as there needs to be a way to allow a Visitor to visit/not visit a cell, without necessarily giving the visit the extra responsibility of making that determination. To accomodate this I separated responsibilities (matching/visiting) by “favouring composition” here is a class that was created to solve this problem in an SRP fashion:

public class ConstrainedCellVisitor : ICellVisitor { private ICellVisitor cell_visitor; private ISpecification<IRange> constraint; public ConstrainedCellVisitor(ICellVisitor cell_visitor, ISpecification<IRange> constraint) { this.cell_visitor = cell_visitor; this.constraint = constraint; } public void visit(IRange cell) { if (constraint.is_satisfied_by(cell)) cell_visitor.visit(cell); } }

The ConstrainedCellVisitor is composed of a raw visitor (that will perform an action against the cell) as well as the specification that will determine whether the cell in questions meets the criteria to be visited with the actual concrete formatting visitor.

The specification interface is something I am sure you have seen me use before (lots of usages, different contexts):

public interface ISpecification<T> { bool is_satisfied_by(T item); }
 
 

All that is needed to finish it off is a very simple configuration api to configure visitors with specifications. Here is one example of a line that builds a visitor and a specification:

yield return new ConstrainedCellVisitor( new ChangeFontSize(8), Cell.occurs_between_columns(3, 8) .and(Cell.occurs_after_row(5)) .or(Cell.is_named("P3")));
 
 

With this model, the ability to add new formatting needs was as simple as adding a new visitor that was only concerned with a specific formatting. This allowed for the incremental growth of formatting visitors as the report demanded it.

This is just one example of where using the power of composition and a couple of “seemingly” simple patterns, can yield results that are extremely extensible results. IMHO the Command and Visitor patterns are 2 of the most powerful and highly underused design patterns a developer has in their toolkit (of course, like with any design pattern, you need to use them wisely).

Comments [2] | | # 
 Saturday, August 30, 2008
Saturday, August 30, 2008 4:49:16 PM (Mountain Standard Time, UTC-07:00) ( Programming )
If you want to carry on setting expectations on void methods on your mocks, just use the following method

public static IMethodOptions when_told_to(this T mock, Action action)
{
     return mock.Expect(action);
}

Here is an example of the usage:


db_connection.when_told_to(x => x.Open()) .Throw(new Exception());

Just another small play on words, but I like the readability of it. Develop With Passion!!
Comments [1] | | # 
 Thursday, July 31, 2008
Thursday, July 31, 2008 2:00:43 PM (Mountain Standard Time, UTC-07:00) ( Programming )

Now that I have been using Vim for a couple of months I feel very comfortable with it. Thanks to someone in my last class who has been a Vim user for years, I have started to use Vim for more than just editing (more on that in a later post). Vim has permeated a lot of the applications that I use:

  • Firefox
  • Visual Studio
  • Word
  • SQL Server Management Studio

 

Anyone who knows me well is aware of the fact that I am a keyboard junkie who is obsessed with keeping my hands as close to home row as possible! This is why for the longest time I have not used the ALT-Insert Resharper shortcut, but rather ALT-R-C-G-I, which is the traversal path to get to the ReSharper generate dialog.

Some of the features that I love about ReSharper also require the use of arrow keys, features such as:

  • Go to next member/tag
  • Go to previous member/tag
  • Move code up
  • Move code down
  • Go to next usage
  • Go to previous usage

I use ViEmu in studio, but also use ReSharper for the awesome features it provides. As cool as the above ReSharper features are, I have never liked having to reach for the arrow keys (or memorize the menu traversal path) when editing with ReSharper. A couple of days ago I decided to use AutoHotkey to allow me to tweak the keyboard so that I could perform all of the above operations using the exact keystrokes as ReSharper except replacing the use of the arrow keys with the appropriate Vim alternative (H,J,K,L). So now I can do the above as follows:

  • Go to next member/tag
    • Original - Alt + Down Arrow
    • Now - Alt + J
  • Go to previous member/tag
    • Original - Alt + Up Arrow
    • Now - Alt + K
  • Move code up
    • Original - Ctrl + Shift + Alt + Up Arrow
    • Now - Ctrl + Shift + Alt + K
  • Move code down
    • Original - Ctrl + Shift + Alt + Down Arrow
    • Now - Ctrl + Shift + Alt + J
  • Go to next usage
    • Original - Ctrl + Alt + Down Arrow
    • Now - Shift + Alt + J
  • Go to previous usage
    • Original - Ctrl + Alt + Up Arrow
    • Now - Shift + Alt + J
  • Generate Code
    • Original - Alt - Insert
    • Now - Alt + I

 

Only the go to next usage functions got a key replacement (Shift instead of Ctrl). Of course, none of the scripts affect the original ReSharper shortcuts, so when I am pairing with someone proficient with ReSharper and not Vim, they do not have an issue as they don't need to use the alternatives (and I can hit the shortcut to temporarily disable ViEmu also). They can carry on using the original ReSharper shortcuts. Notice that I also did the Generate Code so that now I can just hit ALT + I to do the same thing as ALT - Insert (no flight path for the hands at all!!). The nice thing is that now I can pull off all of the above functionality without having to leave home row and I get the benefit of consistent Vim style navigation.

 

Here are the scripts (simplified for brevity):

;=============================
;Process Go to next member/tag
;=============================
$!J::
    Send, !{Down}
return

;=================================
;Process Go to previous member/tag
;=================================
$!K::
    Send, !{Up}
return

;==========================
;Process Move Code Up
;==========================
$^+!K::
    Send, ^+!{Up}
return

;==========================
;Process Move Code Down
;==========================
$^+!J::
    Send, ^+!{Down}
return

;==========================
;Process Go to next usage
;==========================
$+!J::
    Send, ^!{Down}
return

;==========================
;Process Go to previous usage
;==========================
$+!k::
    Send, ^!{Up}
return

;==========================
;Process Generate Code
;==========================
$!I::
    Send, !{Insert}
return

 

Develop With Passion!!

Comments [2] | | # 
 Friday, June 13, 2008
Friday, June 13, 2008 5:47:58 PM (Mountain Standard Time, UTC-07:00) ( C Sharp | Programming )

Having downloaded and started to use Rhino Mocks 3.5 beta pretty much as soon as Oren released. I am very happy with the AAA style (Arrange, Act, Assert) and the readability and brevity it has brought to my tests. The current project I am on has a huge set of tests. Here is an example of using Rhino Mocks, in conjunction with some BDD style naming:

[Concern(typeof (UnitOfWorkFactory))] public class When_a_new_unit_of_work_is_requested_to_be_created : behaves_like_unit_of_work_with_scope_storage_in_play { protected override void because() { sut.Create(); } [Observation] public void Should_access_scoped_storage_to_determine_if_a_unit_of_work_is_already_active() { scoped_storage.was_told_to(item => item.DoesNotContain<IUnitOfWork>()); } } [Concern(typeof (UnitOfWorkFactory))] public class When_creating_a_unit_of_work_and_the_scoped_storage_does_not_contain_an_active_unit_of_work : behaves_like_unit_of_work_with_scope_storage_in_play { private ISession session; protected override void establish_context() { base.establish_context(); session = Dependency<ISession>(); scoped_storage.setup_result(item => item.DoesNotContain<IUnitOfWork>()).Return(true); nhibernate_session_factory.setup_result(item => item.OpenSession()).Return(session); } protected override void because() { sut.Create(); } [Observation] public void Should_store_the_newly_created_unit_of_work_in_scoped_storage() { scoped_storage.was_told_to(item => item.Store(Arg<IUnitOfWork>.Matches(uow => uow != null))); } } [Concern(typeof (UnitOfWorkFactory))] public class When_a_new_unit_of_work_is_requested_and_one_already_exists_in_scoped_storage : behaves_like_unit_of_work_with_scope_storage_in_play { private ISession session; private IUnitOfWork new_unit_of_work; private IUnitOfWork active_unit_of_work; protected override void establish_context() { base.establish_context(); session = Dependency<ISession>(); active_unit_of_work = Dependency<IUnitOfWork>(); nhibernate_session_factory.setup_result(item => item.OpenSession()).Return(session); scoped_storage.setup_result(item => item.Contains<IUnitOfWork>()).Return(true); scoped_storage.setup_result(item => item.Retrieve<IUnitOfWork>()).Return(active_unit_of_work); } protected override void because() { new_unit_of_work = sut.Create(); } [Observation] public void Should_return_a_non_disposing_unit_of_work_proxy() { new_unit_of_work.should_be_an_instance_of<NonDisposableUnitOfWork>(); } }
 

I am no longer using the automocking container so you are probably wondering what the Dependency method call is all about. It is simply a method defined on a base ContextSpecification class whose definition is as follows:

 

[Context] public abstract class ContextSpecification { [SetUp] public void setup() { unit_test_container.Initialize(); establish_context(); because(); } [TearDown] public void teardown() { after_each_specification(); unit_test_container.tear_down_and_unregister_from_dependency_registry(); } protected abstract void because(); protected abstract void establish_context(); protected virtual void after_each_specification() { } protected InterfaceType Dependency<InterfaceType>() { return MockRepository.GenerateMock<InterfaceType>(); } protected InterfaceType Stub<InterfaceType>() { return MockRepository.GenerateStub<InterfaceType>(); } }

And I have some extension methods that wrap the RhinoMocks "assertions" with more language oriented assertions: Instead of AssertWasCalled you get was_told_to, and so on.

 

Develop With Passion!!

Comments [8] | | # 
 Tuesday, June 03, 2008
Tuesday, June 03, 2008 2:33:53 AM (Mountain Standard Time, UTC-07:00) ( Inspiration | Programming )

This post is in direct reference to the brilliant paper titled "The Humble Programmer" written by the software genius Edsger Dijkstra.

If you take the time to read this paper, keep in mind that it was originally published in 1972!! Here are 2 (of the many) that resound very strongly with me:

"But one should not first make the program and then prove its correctness, because then the requirement of providing the proof would only increase the poor programmer's burden. On the contrary: the programmer should let correctness proof and program grow hand in hand. Argument three is essentially based on the following observation. If one first asks oneself what the structure of a convincing proof would be and, having found this, then constructs a program satisfying this proof's requirements, then these correctness concerns turn out to be a very effective heuristic guidance. By definition this approach is only applicable when we restrict ourselves to intellectually manageable programs, but it provides us with effective means for finding a satisfactory one among these."

If that section in bold does not scream TDD to you, then I don't know what will!!

Another good section talking about languages and how we can abuse them is here:

"The competent programmer is fully aware of the strictly limited size of his own skull; therefore he approaches the programming task in full humility, and among other things he avoids clever tricks like the plague. In the case of a well-known conversational programming language I have been told from various sides that as soon as a programming community is equipped with a terminal for it, a specific phenomenon occurs that even has a well-established name: it is called "the one-liners". It takes one of two different forms: one programmer places a one-line program on the desk of another and either he proudly tells what it does and adds the question "Can you code this in less symbols?" —as if this were of any conceptual relevance!— or he just asks "Guess what it does!". From this observation we must conclude that this language as a tool is an open invitation for clever tricks; and while exactly this may be the explanation for some of its appeal, viz. to those who like to show how clever they are, I am sorry, but I must regard this as one of the most damning things that can be said about a programming language"

And finally he shares a piece of advice that is awesome:

"We shall do a much better programming job, provided that we approach the task with a full appreciation of its tremendous difficulty, provided that we stick to modest and elegant programming languages, provided that we respect the intrinsic limitations of the human mind and approach the task as Very Humble Programmers"

Brilliant advice from an equally brilliant man!!

Develop With Passion

Comments [4] | | # 
 Monday, May 19, 2008
Monday, May 19, 2008 2:13:36 PM (Mountain Standard Time, UTC-07:00) ( Programming )

I noticed a small error in the BDD macro that I have just fixed. The text of the macro is below:

Imports System

Imports System.Windows.Forms
Imports EnvDTE
Imports EnvDTE80
Imports System.Diagnostics

Public Module CodeEditor

    Public Sub ReplaceSpacesInTestNameWithUnderscores()
        If DTE.ActiveDocument Is Nothing Then Return
        Dim wrCS As Boolean = DTE.Properties("TextEditor", "CSharp").Item("WordWrap").Value

        Try
            DTE.Properties("TextEditor", "CSharp").Item("WordWrap").Value = False
            Dim selection As TextSelection = CType(DTE.ActiveDocument.Selection(), EnvDTE.TextSelection)
            Dim index As Integer

            selection.SelectLine()
            If selection.Text = "" Then Return

            Dim methodIndex As Integer = selection.Text.IndexOf("public void ")
            Dim classIndex As Integer = selection.Text.IndexOf("public class ")

            If (methodIndex < 0 AndAlso classIndex < 0) Then Return

            index = CType(IIf(methodIndex >= 0, methodIndex, classIndex), Integer)

            Dim prefix As String = CType(IIf(methodIndex >= 0, "public void ", "public class "), String)
            Dim whiteSpace As String = selection.Text.Substring(0, index)
            prefix = whiteSpace + prefix
            Dim description As String = selection.Text.Replace(prefix, String.Empty).Trim
            Dim text As String = prefix + description.Replace(" ", "_").Replace("'", "_") + vbCrLf
            selection.Delete()
            selection.Insert(text)
            selection.LineUp()
            selection.LineUp()
            selection.SelectLine()
            If selection.Text.Trim = "{" Or selection.Text.Trim = "}" Or selection.Text.Trim = "" Then
                If selection.Text.Trim = "{" Or selection.Text.Trim = "}" Then
                    selection.Insert(selection.Text.Replace(vbCrLf, "") + vbCrLf)
                ElseIf selection.Text.Trim = "" Then
                    selection.Delete()
                End If
            End If
            selection.LineDown()
            selection.LineDown()
            selection.EndOfLine()
        Catch ex As Exception
            MsgBox(ex.Message)
        Finally
            DTE.Properties("TextEditor", "CSharp").Item("WordWrap").Value = wrCS
        End Try
    End Sub
End Module

Comments [1] | | # 
 Monday, May 12, 2008
Monday, May 12, 2008 3:20:09 PM (Mountain Standard Time, UTC-07:00) ( Programming )

I just completed a reorganizing of the solution that I am currently working on. I now have only 2 projects in the solution. I use to have 3 project:

  • {ApplicationName} - This contained the project for the application itself, all of the logical layers lived in this project.
  • {ApplicationName}.Test - The unit tests for the Application (integration and unit)
  • {ApplicationName.Build - All of the artifacts related to managing the build process

After the reorg that just took place over the last 1 hour it is now:

  • {ApplicationName} - Same as before, except now each spec/specs live beside the code it is testing.
  • {ApplicationName}.Build - Same as before

Thanks to the power of ReSharper and an existing NAnt build file that I was already using to manage the project build/compilation/test ... It took me 40 minutes to do the file shuffling. ReSharper helped out with the namespace changes. 3 lines of xml added to the build script (no other changes required) and I am back in business!!

I love ReSharper!! And yes, I am running the latest nightly build (797) and it has been running amazingly. I currently have Solution Wide Error Analysis turned off, as it seems to slow things down a little.

Comments [7] | | # 
 Friday, May 02, 2008
Friday, May 02, 2008 7:04:51 PM (Mountain Standard Time, UTC-07:00) ( Programming )

I am currently trying to add some polish to the application that I am working on, and I stumbled upon this post here that pointed to a location that contained a zip file with a majority of the standard icons that Microsoft uses in both Visual Studio and the Office Suite. For those of you running Visual Studio 2008 you can find the zip file in the following location:

C:\%vs install path%\Common7\VS2008ImageLibrary\1033

In that folder you will find a zip file named: VS2008ImageLibrary.zip.

Just extract the contents of that zip file and you have more icons that you can probably work with!!

Develop With Passion!!

Comments [3] | | # 
Friday, May 02, 2008 2:01:15 PM (Mountain Standard Time, UTC-07:00) ( Agile | Programming )

I was in the gym this morning (at one point I will write a whole post on a good exercise routine for those of you who are curious) and I was just about to finish the bench press. As I place the bar back up on the rack I realized that I probably had a little more in me, but I lacked the aid of a spotter who could provide me with a bit of incentive/support in the event that I would not be able to get another rep out.

This got me thinking about the term spotting. Here are a couple of quotes about spotting taking from the wikipedia definition:

"Spotting, in weight or resistance training, is the act of supporting another person during a particular exercise, with an emphasis on allowing the participant to lift or push more than he could normally do safely."


Correct spotting involves knowing when to assist with a lift and encouraging a training partner to push beyond the point in which they would normally 'rack' (return the weight to its stationary position) the weight....."


This actually got me thinking about the pair programming process and the concept of being a spotter in the software development realm. When two people are actively pairing on a problem there is usually only 1 person who is typing while the other person is observing and conversing with the person doing the driver. The person not typing is not there in a passive or static role. They are


"actively supporting another person during the programming exercise"


They will be:

  • Catching potential design flaws the person driving may be missing
  • Providing ideas to a "driver" who may be stuck without an idea of how to go forward
  • Positively criticizing code choices that will result in a maintenance issue a couple of minutes from now (compounded if you add 6 months on top of that). Things such as cryptic variable names, class names that do not fit with the domain or problem space being tackled, long methods...
  • Taking the weight (keyboard) from the person entirely if they are completely unable to move forward

I think the last sentence in the wikipedia description is interesting:

"As a general rule to prevent injury and ensure safety spotters should have the strength to be able to control the weight should their training partner's strength completely fail. This is known as a "bail out"."

When two programmers who are at a similar skill level get together to pair program a design problem, it provides a lot of stimulation, challenge, and idea bouncing that may not have happened had there been significant gaps in the skill level between the 2 developers. It also provides the added benefit of the "bail out" when the person driving the problem out in code gets stuck and they fail to keep moving forward, they can pass of the reigns to their pair while they regain their mental composure to tackle the problem once more.

Most of us know that it is a bad idea to attempt a heavy bench press without the aid of someone to spot us. In the same way, when you are facing down a particularly difficult challenge would you not prefer to have a spotter to aid you through the process?

Develop With Passion!!

Comments [1] | | # 
 Tuesday, April 15, 2008
Tuesday, April 15, 2008 3:59:41 AM (Mountain Standard Time, UTC-07:00) ( Programming | Tools )

For the last couple of weeks, I have been integrating Vim and a complementary set of tools into my development toolkit. I am firmly on board with what the pragmatic programmers say:

"Learn a good editor, and learn it well!!"

I am thoroughly impressed with Vim, Viemu etc. Last week I was recommended a registry hack that would allow my Caps Lock key to have the same behaviour as the ESC key. This results in a much smoother experience when using Vim.

So far, I am loving the reg hack and much prefer the need to not have to move my hand to hit the ESC key. Here is the text of the reg file:

Windows Registry Editor Version 5.00

[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Keyboard Layout]
"Scancode Map"=hex:00,00,00,00,00,00,00,00,02,00,00,00,01,00,3a,00,00,00,00,00

[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Keyboard Layout\DosKeybCodes]
"00000804"="ch"
"00000408"="gk"
"00010408"="gk"
"00020408"="gk"
"00050408"="gk"
"0001041f"="tr"
"0000041f"="tr"
"00000423"="us"
"00000402"="bg"
"00000419"="ru"
"00010419"="ru"
"00000c1a"="us"
"00010c1a"="us"
"00000422"="us"
"00010402"="us"
"00020402"="bg"
"00030402"="bg"
"00020422"="us"
"00000412"="ko"
"00000425"="et"
"00000426"="us"
"00010426"="us"
"00000427"="us"
"00000411"="jp"
"00000404"="ch"
"0000041C"="us"
"0000041a"="yu"
"00000424"="yu"
"00000405"="cz"
"00010405"="cz"
"0000040e"="hu"
"0001040e"="hu"
"00000415"="pl"
"00010415"="pl"
"00000418"="ro"
"00010418"="ro"
"00020418"="ro"
"0000041b"="sl"
"0001041b"="sl"
"00000442"="tk"
"00000813"="be"
"0000080c"="be"
"00001009"="us"
"00000c0c"="cf"
"00010c0c"="cf"
"00000406"="dk"
"00000413"="nl"
"0000040b"="su"
"0000040c"="fr"
"00000407"="gr"
"00010407"="gr"
"0000040f"="is"
"00001809"="us"
"00000410"="it"
"00010410"="it"
"0000080a"="la"
"00000414"="no"
"00000816"="po"
"00000416"="br"
"0000040a"="sp"
"0001040a"="sp"
"0000041d"="sv"
"0000100c"="sf"
"00000807"="sg"
"00000809"="uk"
"00010409"="dv"
"00030409"="usl"
"00040409"="usr"
"00020409"="us"
"00000409"="us"
"00000452"="uk"
"0000046e"="sf"

[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Keyboard Layout\DosKeybIDs]
"00010408"="220"
"00020408"="319"
"0001041f"="440"
"0000041f"="179"
"00010415"="214"
"00000442"="440"
"00000410"="141"
"00010410"="142"

Create a reg file and copy the contents into it, then merge the file into your registry. Make sure that you want to not have normal use of your caps lock key.

Develop With Passion!!

Comments [11] | | # 
Tuesday, April 15, 2008 3:48:56 AM (Mountain Standard Time, UTC-07:00) ( Programming )

Ever since I received the BDD test naming macro from Scott Bellware last year, it has gone through several iterations of improvements (mostly due to students taking the time to tune up the macro).

Of all of the enhancements to the macro, none of them have done as much for the speed of the macro of the enhancements made by:

Todd Berry and Casey Gum

The macro now runs so fast that it is a joy to watch (you have to be quick). For those of you who are switching to leveraging context style BDD testing, you may want to pick up the macro and integrate it into your IDE:

 

Imports System

Imports System.Windows.Forms
Imports EnvDTE
Imports EnvDTE80
Imports System.Diagnostics

Public Module CodeEditor

    Public Sub ReplaceSpacesInTestNameWithUnderscores()
        If DTE.ActiveDocument Is Nothing Then Return
        Dim wrCS As Boolean = DTE.Properties("TextEditor", "CSharp").Item("WordWrap").Value

        Try
            DTE.Properties("TextEditor", "CSharp").Item("WordWrap").Value = False
            Dim selection As TextSelection = CType(DTE.ActiveDocument.Selection(), EnvDTE.TextSelection)
            Dim index As Integer

            selection.SelectLine()
            If selection.Text = "" Then Return

            Dim methodIndex As Integer = selection.Text.IndexOf("public void ")
            Dim classIndex As Integer = selection.Text.IndexOf("public class ")

            If (methodIndex < 0 AndAlso classIndex < 0) Then Return

            index = CType(IIf(methodIndex >= 0, methodIndex, classIndex), Integer)

            Dim prefix As String = CType(IIf(methodIndex >= 0, "public void ", "public class "), String)
            Dim whiteSpace As String = selection.Text.Substring(0, index)
            prefix = whiteSpace + prefix
            Dim description As String = selection.Text.Replace(prefix, String.Empty).Trim
            Dim text As String = prefix + description.Replace(" ", "_").Replace("'", "_") + vbCrLf
            selection.Delete()
            selection.Insert(text)
            selection.LineUp()
            selection.LineUp()
            selection.SelectLine()
            If selection.Text.Trim = "{" Or selection.Text.Trim = "}" Or selection.Text.Trim = "" Then
                If selection.Text.Trim = "{" Or selection.Text.Trim = "}" Then
                    selection.Insert(selection.Text.Replace(vbCrLf, "") + vbCrLf)
                ElseIf selection.Text.Trim = "" Then
                    selection.Delete()
                End If
                selection.Insert(whiteSpace + IIf(methodIndex >= 0, "[Test]", "[TestFixture]") + vbCrLf)
            End If
            selection.LineDown()
            selection.LineDown()
            selection.EndOfLine()
        Catch ex As Exception
            MsgBox(ex.Message)
        Finally
            DTE.Properties("TextEditor", "CSharp").Item("WordWrap").Value = wrCS
        End Try
    End Sub
End Module

 

Develop with Passion!!

Comments [4] | | # 
 Wednesday, December 19, 2007
Wednesday, December 19, 2007 10:26:48 PM (Mountain Standard Time, UTC-07:00) ( C Sharp | Programming )

Got some feedback on my MappingEnumerable post. People wanted to see me leveraging some of the new language features (specifically linq).

I can leverage linq to change the extension method to eliminate the need for the MappingEnumerable (which was brought in to mitigate the absence of extension methods) and replace it with the following code: 

public static IEnumerable<Output> MapAllUsing<Input,Output>(this IEnumerable<Input> items,IMapper<Input,Output> mapper) { return from item in items select mapper.MapFrom(item); }

K. Scott Allen had the suggestion to use property initializers:  

IEnumerable<Department> departments = departmentRepository.GetAllDepartments(); return from d in departments select new DepartmentDisplayItemDTO() { ID = d.ID, Name = d.Name };

Which you can definitely do if you so wish, that specific dto is completely immutable so the above would not work, but could be changed to accommodate.

It is important to note that the IMapper<Input,Output> interface is an interface that can be implemented to perform all sorts of mapping. Some examples of how I have used this in the past are:

  • Mapping from DB to Domain
  • Mapping from Domain to DTO
  • Mapping from Errors to ScreenElements
  • Mapping from DTO to Presentation Model
  • ….

You are only limited by your imagination. And because each mapper has a single MapFrom method, it is very easy to test specific implementations of the interface, you can even create a non generic IMapper interface that you can use for completely reflective scenarios (picture externally defined OO mapping).

K. Scott Allen also mentions DTO Tax, and I don’t think his point is specific to just DTO’s but the cost of mapping in general. Focusing on 1 mapping at a time, refactoring out the duplication and moving on; is a way that you can grow and add all sorts of mapping in a very organic way to your applications.

Develop With Passion!!

Comments [3] | | # 
Wednesday, December 19, 2007 1:44:14 PM (Mountain Standard Time, UTC-07:00) ( C Sharp | Programming )

With a newfound interest in leveraging the AutoMockingContainer (credit to James for convincing me of this approach) here is the code for my base class used to write BDD style interaction based tests:

public abstract class Specification { private MockRepository mockery; private AutoMockingContainer container; protected MockRepository Mocks { get { return mockery; } } protected AutoMockingContainer Container { get { return container; } } [SetUp] public void BaseSetup() { mockery = new MockRepository(); container = new AutoMockingContainer(mockery); container.Initialize(); Before_each_spec(); } [TearDown] public void TearDown() { After_Each_Spec(); } protected virtual void After_Each_Spec() { } public IDisposable PlayBackOnly { get { using (Record) { } return PlayBack; } } public void BackToRecord(object mockObject) { Mocks.BackToRecord(mockObject); } public IDisposable Record { get { return Mocks.Record(); } } public IDisposable PlayBack { get { return Mocks.Playback(); } } public abstract void Before_each_spec(); public Item CreateSUT<Item>() { return container.Create<Item>(); } public Interface CreateStrictMockOf<Interface>() { return mockery.CreateMock<Interface>(); } public IEnumerable<T> CreateMockEnumerable<T>() { return CreateMock<IEnumerable<T>>(); } public T Mock<T>() where T : class { return container.Get<T>(); } public void ProvideAnImplementationOf<Interface, Implementation>() { container.AddComponent(typeof (Implementation).FullName, typeof (Interface), typeof (Implementation)); } public void ProvideAnImplementationOf<Interface>(object instance) { container.Kernel.AddComponentInstance(instance.GetType().FullName, typeof (Interface), instance); } protected Interface CreateMock<Interface>() { return Mocks.DynamicMock<Interface>(); } }

I changed some of my original method names to match up with what Dave was doing (for a bit of consistency).Here is an example of a testfixture that leverages this as the base (this test happens to use an explicit CreateSUT method, vs the one provided by the AutoMockingContainer):

 

[TestFixture] public class When_told_to_visit_all_items : Specification { private IVisitor<int> visitor; private RichList<int> numbers; private IEnumerableActions<int> sut; private IEnumerableActions<int> CreateSUT() { return new EnumerableActions<int>(numbers); } public override void Before_each_spec() { numbers = new RichList<int>(); numbers.Add(1); numbers.Add(2); sut = CreateSUT(); visitor = CreateMock<IVisitor<int>>(); } [Test] public void Should_tell_visitor_to_visit_all_items_in_the_enumerable() { using (Record) { foreach (int i in numbers) { visitor.Visit(i); } } using (PlayBack) { sut.VisitAllItemsUsing(visitor); } } }

Develop With Passion!

Comments [1] | | # 
Wednesday, December 19, 2007 1:22:00 PM (Mountain Standard Time, UTC-07:00) ( C Sharp | Programming )

I just upgraded the project to a VS2008 project and am now starting to demonstrate (and will continue to do so in the new year) how to integrate some of the new language features.

This means that if you don’t have .Net 3.5 installed on your machine you will not longer be able to run the NAnt build. Furthermore, if you do not have VS2008 on your machine you will not be able to open the solution.

Sorry!!

 

Develop with Passion!!

Comments [6] | | # 
Wednesday, December 19, 2007 11:03:44 AM (Mountain Standard Time, UTC-07:00) ( C Sharp | Programming )

In my infrastructure layer of my projects I regularly include the following interface:

public interface IMapper<Input, Output> { Output MapFrom(Input input); }

This interface should be fairly self-explanatory, it takes in an item of type Input and spits out an item of type Output. For those who care about details (and I do) it is also good to note that this interface matches the signature for a Converter generic delegate.

One of the (many) places that I use implementations of this interface is in the service layer to marshal data back up to the higher level layers as DTOS. Here is an example of a simple Mapper:

public class DepartmentDisplayItemDTOMapper : IDepartmentDisplayItemDTOMapper { public DepartmentDisplayItemDO MapFrom(IDepartment department) { return new DepartmentDisplayItemDO
(department.Name, department.Id); } }

One of the ways that I would have leveraged this in the past would have been to inject the service layer component with the appropriate mapper and then map items that were returned from the repository in place.

Here is another alternative that takes advantage of a type I am calling a MappingEnumerable<T>. Take a look at the code for the class:

public class MappingEnumerable<Input, Output> : IMappingEnumerable<Input, Output> { private IMapper<Input, Output> mapper; private IEnumerable<Input> inputItems; public MappingEnumerable(IMapper<Input, Output> mapper, IEnumerable<Input> inputItems) { this.mapper = mapper; this.inputItems = inputItems; } IEnumerator<Output> IEnumerable<Output>.GetEnumerator() { return MapAllFrom(inputItems).GetEnumerator(); } public IEnumerator GetEnumerator() { return ((IEnumerable<Output>) this).GetEnumerator(); } private IEnumerable<Output> MapAllFrom(IEnumerable<Input> input) { foreach (Input item in input) { yield return mapper.MapFrom(item); } } }

Using this class from the service layer is as simple as:

 

public IEnumerable<DepartmentDisplayItemDO> GetAllSubdepartmentsOf(long departmentId) { IDepartment parentDepartment = departmentRepository.FindBy(departmentId); IEnumerable<IDepartment> subdepartments = departmentRepository.AllSubDepartmentsOf(parentDepartment); return new MappingEnumerable<IDepartment, DepartmentDisplayItemDO> (subdepartments, departmentDisplayItemDTOMapper); }

Notice that the MappingEnumerable decorates the existing enumerable with mapping behaviour. Because the MappingEnumerable is itself an implementation of an IEnumerable<T> interface, the mapping of each item will not start until the iteration of the enumerable happens.

Taking this class and applying it in the 3.5 world (I prefer using components vs free floating extension methods) can result in the following:

IDepartment parentDepartment = departmentRepository.FindBy(departmentId); IEnumerable<IDepartment> subdepartments = departmentRepository.AllSubDepartmentsOf(parentDepartment); return subdepartments.MapAllUsing(departmentDisplayItemDTOMapper);

Where MapAllUsing is an extension method on IEnumerable which lives in my infrastructure layer. The simplified implementation of MapAllUsing just delegates the work to the MappingEnumerable class: 

public static IEnumerable<Output> MapAllUsing<T,Output>(this IEnumerable<T> itemsToMap,IMapper<T,Output> mapper) { return new MappingEnumerable<T, Output>
(mapper,itemsToMap); }

One more short example to show how I leverage this pattern in my apps take a look at this method on a DatabaseGateway interface:

IEnumerable<DataRow> GetASetOfRowsUsingA(IQuery query);

A simple method to return an enumerable of DataRows. You can now leverage this to do things like:

public IEnumerable<DomainObject> GetAllUsing(IQuery query) { return gateway.GetASetOfRowsUsingA(query).MapAllUsing(dbMapper); }

Where the mapper in this case knows how to hydrate datarows into domain objects of the specific (DomainObject) type the mapper is defined for.

One of the things I tell people in class (and work) is that IEnumerable is the ultimate Separated Interface and this post just scratches the surface of the things you can do by just getting creative with the IEnumerable interface.

Develop With Passion!!

Comments [2] | | # 
 Thursday, November 29, 2007
Thursday, November 29, 2007 10:36:09 AM (Mountain Standard Time, UTC-07:00) ( Agile | Programming )

I have received a number of good responses from people who have a couple of aesthetic issues with the BDD style naming that I am starting to use. Let me clarify, I have been using the natural sentence style test naming since Scott introduced me to it in earlier in the year. I have not used the context/specification style test naming on a project yet, though it is my intent to write each successive test from this point forward in that style and if I feel pain points I will let you know.

From my experience so far here are some tips that I think will resolve the issues that the people who are trying to use it will find:

Issue 1 – “I ended up really not liking those fixture names because I felt it was hard to find fixtures for specific classes, and navigate with Resharper Type navigation.  Was wondering what naming convention you came up with for fixtures?”

A: My recommendation for this is to create a single test class in your test project called $SystemUnderTest$Specs. Where SystemUnderTest corresponds to the name of the class that you will be testing. This is just a grouping construct for all of the “Contexts” that will be run against that fixture. Inside the “Specs” class, you will create classes for each of the different contexts. Here is an example of one that I just rewrote the tests for the ShoppingCart class is the nothinbutdotnetweb.app project using this new style and I personally have to say that it was an awesome experience. One of the things that I found was that I could copy the body of one fixture and change the name to reflect the new context and I could focus solely on the interactions and behaviour that is pertinent to that particular context. Take a look at the Report that is generated when run against the specs in the ShoppingCartSpecs class:

  • When a product is added that is not already in the cart
    • The cart item factory should be used to create a cart item for the product being added.
  • When an item is added
    • The item count should be incremented
    • The item should be added to the underlying list
  • When the same product is added again
    • The item factory should not be leveraged
    • The quantity of the item should be incremented
  • When changing the quantity of a product in the cart
    • The item should be updated with the new quantity
  • When changing the quantity of a product causes the item to be empty
    • The item should be removed from the cart
  • When changing the quantity of a product that is not in the cart
    • Nothing should happen
  • When a product is removed from the cart
    • The item representing the product should be removed
    • The number of items in the cart should decrease
  • When asked to remove a product that is not already in the cart
    • Nothing should happen
  • When the cart is emptied
    • There should be no more items
  • When asked for the quantity of a product
    • The cart item representing the product should be asked for its quantity
    • The result should be the quantity of the item for the product
  • When asked to calculate the total cost
    • Should be the sum of the total cost for all items

 

One of the things you will notice about the tests in these fixtures compared to the others in the rest of the project (so far) is the use of Setup to stress the context setup. I added a virtual method to the AutoMockingTest base called because, which calls out the action being invoked on the SUT.

This actually resulted is some tests that contained no body whatsoever, and the ones with assertions actually only needed one assertion.

This is a learning experience for me to, but so far, I am loving the expressiveness and focus this style of testing brings to the table.

By grouping all of the fixtures into the ShoppingCartSpecs class, you can solve the navigability issue.

 

The second issue I received was:

“Quick question ... while the idea is great, it doesn;t flow for me, as ReSharper keeps cutting in and completing my words for me - Intellisence is great, but in this context is is annoying as hell ...

 

How do you avoid this problem?”

 

 

A – This is actually a ReSharper setting that I have had turned off pretty much since I started using ReSharper:

  • Go to ReSharper – Options
  • Select the Intellisense item in the left nav bar
  • Uncheck Letters and Digits in the Completion Behaviour pane on the right!!

That’s it. Now you can write you natural sentences without ReSharper getting in your way. Since I have been without this setting since ReSharpers inception, I have gotten quick at using ALT-SPACE/CTRL-ALT-SPACE a lot, this may take a bit of getting used to for the people who were use to the Letters and Digits autocompletion behaviour.

 

Again, as far as quickly navigating to the tests for a sut, you can just go CTRL-SHIFT-N and then start typing in the significant letters for the Spec class, in this case it would be:

 

CTRL-SHIFT-N -> SCS

 

Because all of the fixtures will be contained in the file but there will be no ShoppingCartSpecs type. I guess you could create one as a nesting construct, but that is what the file is for.

 

Again, let me stress that this Context/Specification style naming is a little new for me, and there is a possibility that the tests in the ShoppingCartSpecs that have no assertions could be a smell (I’ll get that verified by Scott in a little while), I already see the benefits from both the documentation perspective as well as the ability to truly only focus on one specific context at a time.

 

Develop With Passion.

 

Comments [3] | | # 
 Wednesday, November 28, 2007
Wednesday, November 28, 2007 11:59:42 PM (Mountain Standard Time, UTC-07:00) ( .Net 2.0 | Agile | C Sharp | Programming )

Having received a bunch of emails in the past couple of weeks from people who have been asking me questions with regards to Passive View/Supervising controller patterns for web applications. I needed to let people know that for the last couple of months I have been developing web apps in a completely MVC style which eliminates the need for patterns like Passive View/ Supervising Controller.

For the people who are using the MVP pattern in their (web) applications I personally would now lean to the Supervising Controller style as it eliminates a lot of necessary chattiness between the view and the presenter. It also lends itself to much more simple unit tests.

Having gotten back into the Smart Client realm, I am once again reminded of the importance of patterns like Supervising Controller and presentation model as becoming essential to ensuring correct separation of responsibilities.

For my web applications, however, all I use now is a:

  • Front Controller
  • Commands
  • View Templates (ASPX style!!)

Here is an example of what I mean, for the nothinbutdotnetstore.web.app project that is currently hosted on google code, here is the Command that processes getting a list of the main departments in the store for viewing:

 

using NothinButDotNetStore.Infrastructure; using NothinButDotNetStore.Infrastructure.Container.Common; using NothinButDotNetStore.Tasks; using NothinButDotNetStore.Web.FrontController; namespace NothinButDotNetStore.Web.DepartmentBrowser { public class ViewMainDepartments : ICommand { private ICatalog catalog; private IRequestContext requestContext; private IViewEngine viewEngine; public ViewMainDepartments(IHttpContext context) : this(context, DependencyResolver.GetImplementationOf<IRequestContextFactory>().CreateFrom(context), DependencyResolver.GetImplementationOf<IViewEngine>(), DependencyResolver.GetImplementationOf<ICatalog>()) { } public ViewMainDepartments(IHttpContext context, IRequestContext requestContext, IViewEngine viewEngine, ICatalog catalog) { this.catalog = catalog; this.viewEngine = viewEngine; this.requestContext = requestContext; } public void Execute() { requestContext.AddToStateBag(ViewBagItem.Departments, catalog.GetMainDepartments()); viewEngine.Display(Views.ViewDepartments); } } }
 
Here is the complete ASPX (View Template) that gets rendered for that command executing:
 
 
<%@ MasterType VirtualPath="~/Store.master" %> <%@ Page Language="C#" AutoEventWireup="true" Inherits="System.Web.UI.Page" MasterPageFile="~/Store.master" %> <%@ Import namespace="NothinButDotNetStore.Web.FrontController"%> <%@ Import namespace="NothinButDotNetStore.Web"%> <%@ Import namespace="NothinButDotNetStore.Infrastructure"%> <%@ Import namespace="NothinButDotNetStore.DTO"%> <asp:Content ID="content" runat="server" ContentPlaceHolderID="childContentPlaceHolder"> <p class="ListHead">Select An Isle</p> <table> <% int rowIndex = 0; %> <% foreach (DepartmentDisplayItem dto in ViewBag.GetItem(ViewBagItem.Departments)) { %> <tr class='<%=(rowIndex++ %2 ==0 ? "nonShadedRow" : "shadedRow" ) %>'> <td> <a href='<%= Url.ToBeProcessedBy(CommandNames.ViewSubDepartments) .AddPayloadValue(PayloadKeys.DepartmentId,dto.Id).Build() %>'> <%=dto.DepartmentName %> </a> </td> </tr> <% } %> </table> </asp:Content>

There is no code behind for this aspx page. The logic in the aspx file is there because it is rendering related logic. This aspx page does not talk to a service layer or domain objects or even a data access layer. It reaches into a ViewBag looking for information that it can render, and then it proceeds to do exactly what it should, render the information. What may not be immediately obvious is that this is a plain aspx file with no codebehind file. The page inherits from System.Web.UI.Page.

As far as testability of this style of development, here is a sample test for one behaviour of the ViewMainDepartments command:

[RunInUnitTestContainer] [Test] public void Should_populate_the_context_with_the_departments_to_display() { ICommand sut = CreateSUT<ViewMainDepartments>(); IEnumerable<DepartmentDisplayItem> results = CreateMock<IEnumerable<DepartmentDisplayItem>>(); using (Mocks.Record()) { Expect.Call(mockCatalog.GetMainDepartments()).Return(results); mockRequestContext.AddToStateBag(ViewBagItem.Departments, results); } using (Mocks.Playback()) { sut.Execute(); } }
 
 
 

In the next little while I am going to shed some more light on this approach to web application development. IMHO, the separation of concerns for web applications written in this style is much greater than when trying to stuff in a pattern that (again IMHO) did not fit well for the technology, and was leveraged for the sake of increased testability.

Comments [2] | | # 
Wednesday, November 28, 2007 11:01:52 PM (Mountain Standard Time, UTC-07:00) ( .Net 2.0 | .Net 3.0 | Agile | C Sharp | Continuous Integration | Patterns | Programming | Tools )

I finally set up a googlecode project to host source code for the various things I have been doing over the last year. The first major significant contribution is of course the code drop that I promised a week ago now!!

The application is the start of what I hope will evolve to be a great learning resource for lots of things related to .Net development. The application does not currently cover any of the “extra” topics that I did not have time to get covered in the course. This is perfect because as request come in from people (including past students) asking how to tackle a certain problem, I will use this application as the demonstration area where I can tackle the problem, and update the code base, and you will be able to update your local copy and carry on.

I am currently in the midst of a large Smart Client application that I am hoping to be able to harvest pieces of code out and do the exact same thing except for the smart client realm. I have much more experience developing in the smart client realm and that is where I feel most comfortable, so I am looking forward to be able to do another code drop (for a different application) in a couple of months.

I am going to write up another post about the Web Application as it is built very differently from traditional .Net based web applications. In following with the theme for my courses, there are currently no 3rd party frameworks (other than log4net) that have come into play. My goal with this web app is to demonstrate to people how far we can push raw .Net. The goal being that expanding their knowledge of how to creatively leverage .Net, they will be better prepared to jump into frameworks that they may currently feel daunted by. As time goes by, I will swap pieces of the application out with components that people are asking to see meaningful samples on:

  • NHibernate
  • Castle
  • Prototype
  • JQuery
  • ..*

As the app stands right now I see it as the beginning of what will shape up to be a pretty mean machine!!

I am going to post a screencast that will show people how to get started working with the web application. For people who are eager to get going right now, here are the quick and simple steps without a lot of explanation (that will come in the next post):

  • Anonymously checkout the trunk from the google code repository using the following svn command line:
    svn checkout http://jpboodhoo.googlecode.com/svn/trunk/ jpboodhoo-read-only
  • Navigate to the checkout folder
  • Go into the build folder
  • Copy local.properties.xml.template and paste it into the same directory, then rename the copied file to local.properties.xml
  • Open up the local.properties.xml file with your favourite text editor.
  • Modify any of the settings in the file that are different on your machine.
  • Open up a command prompt and navigate to the build directory of the code.
  • type: build load.data and hit enter.
  • type: build test.all.woc
  • type: build run
  • The last task should fail (I haven’t automated everything yet)
  • Create a virtual directory called nothinbutdotnetstore that points at the following location (this location is created after you attempt to run the build run task) : ${checkoutfolder)\build\deploy\web\app
  • After successfully creating the virtual directory try the build run task again.
  • If the web browser pops up pointed at a web page (for the app) you are in business. Feel free to click through the first set of pages that are implemented (only 3 pages are currently implemented).

As far as what I have planned to implement in the web app (that is currently not implemented):

  • Build out a more extensive domain model that encompasses some more advanced scenarios of the application (especially around order processing).
  • Unit Of Work for the service layer
  • Implement a lightweight OR/M layer
  • Integrate some UI frameworks like prototype
  • Eliminate Master Pages completely and switch to a much more elegant template view pattern.
  • Introduce a more robust container (as the current one is a simple dictionary wired up in a simple procedural fashion).
  • Introduce the concepts of lifecycles for the items in the container. Right now, everything wired into the container is essentially a singleton.
  • Introduce CSS based layout for the web pages (working with a designer on this one).
  • Bring security concerns into play
  • Demonstrate how to effectively manage sessions
  • ……lots,lots,lots more!!!

Obviously I will be leaning on people checking out the code and playing around with it and submitting requests for things they would like to see.

There are a couple of things that you will immediately notice about the application:

  • Clean front controller implementation with ASPX pages as the template views. There are no code behind pages in this web application. All web requests are handled by command objects that interact with the service layer, push the details into a “ViewBag” and then choose which view to render.
  • Logical layers in the project are separated using simple folders and namespaces (not full blown projects)
  • Build automation is its own project in the solution (props to Jay Flowers for this inspiration)
  • The current container implements (CustomDependencyContainer) is very simple and is handled by a big procedural application startup task.
  • Compile time support for the database layer. A couple of classes ago I introduced the concept of a generic TableColumn<T> type. In England after introducing this concept Scott Cowan leveraged his knowledge of MyGeneration to automatically generate strongly typed table definitions that we could leverage to do mapping (trust me when I say, this is nothing like datasets). Until moving into OR/M concepts deeper this gives a good place to start as the generation of the TableDefinitions is linked to whenever the SQL files change, so you will get compile errors if column types are now mismatched etc…

There are lots of other things I could talk about, but this code really is the start of what I see being a long running conversation between myself and other people wanting to learn. In all honesty for all of the emails I have not paid attention to this year, hosting code through google will allow me to answer peoples questions in a much more meaningful way as I can point them at this site to see the implementation of the code they had questions about.

I am going to be placing all of the code for presentations that I have done for the last year as well as continue to update it with the source code that comes out of new courses that will be coming out in the new year, and the DNRTv episodes.

Once again, the application is currently in its infancy, but as people start sending in the requests I now will have a venue and example to add upon to answer questions in a much more timely fashion!!!

 

Develop With Passion!!!

 

 

Comments [12] | | # 
 Wednesday, November 21, 2007
Wednesday, November 21, 2007 1:30:10 AM (Mountain Standard Time, UTC-07:00) ( Agile | Programming )

I had to laugh when I read “TDD Ain’t No Snowboarding from Alessandro Burrato. It is a direct counter to my TDD is Like Snowboarding post!!

His experience of TDD is very different than the experience I documented based off of my experience introducing it to clients. And I feel that his recollection of the experience is definitely one that I would like to see more in the clients that I engage and the people that I talk to

He makes one very good point that I can’t stress enough to people who spend their days reading blogs about the great stuff that people are doing, to quote him:

“If, and only if, you stop seeking pre-cooked answers from those who already tried it and start friggin’ DOING something.”

At one point or another, practical knowledge of a topic far outweighs any theories you may have built up in your head!!

Nice post Alessandro.

 

Comments [1] | | # 
 Sunday, November 11, 2007
Sunday, November 11, 2007 5:48:00 AM (Mountain Standard Time, UTC-07:00) ( .Net 2.0 | .Net 3.0 | Agile | C Sharp | Programming | Training )

A lot of people will probably say it is about time!! I am taking the source code that just got driven out from this last week of Nothin But .Net and I am going to make it publicly available from my blog. I am hoping to release it by the end of the week. The reason that I can’t release it yet, is that there are lots of concepts that I wanted to cover in class that I did not have time too, so I am going to spend a bit of time fleshing out the code base to include all of the concepts that were missed (by student request)

Keep in mind that Nothin But .Net is a course about fundamental software development practices with a bit of a .Net slant. Here are some of the things you will be able to see in the code base:

  • How Test Driven Development was used to drive out the functionality of screens in the application in a top down fashion
  • The benefit of using Data Transfer objects not as a marshaling tool, but as a tool to let the needs of the UI not influence unecessary changes to the domain model
  • The benefits of leveraging layered architecture
  • Why you don’t need lots of projects in your enterprise solutions if you are using an automated build (take  a look at the following screenshot to get an idea for the solution structure
  • Clean Front Controller implementation so that you can eliminate the need for messy Passive View/Supervising Controller implementations just for testability of the web form world
  • Good practices around mixing both interaction and state based testing
  • Test partitioning (integration, unit, acceptance)
  • My current project build structure
  • How to avoid the overspecification problem with interaction based testing
  • Rhino Mocks and leveraging the automocking container (thanks James for getting me hooked on this thing)
  • Fluent Interfaces
  • Build Automation
    • NAnt compilation as an effective tool for pruning dead code that studio does not show
    • NAnt as a build tool
    • NAnt as your compiler and test runner
    • Build file partitioning
      • Use of filesets
    • Machine agnostic build files through use of local property files
  • Unit Testing
    • Focusing on one thing at a time
    • Incremental testing
    • Breaking reliance on setup methods
  • MBUnit
    • Decorators used effectively
  • Design Patterns
    • Visitor
    • Factory
    • Data Transfer Object
    • Adapter
    • Proxy
    • Mapper
    • Unit Of Work (lots of people have been bugging me about this for a while)
    • Lazy Loading
    • IOC
    • Gateway (and Static Gateway)
    • Service Layer
    • Identity Map
    • Data Mapper
    • Database Gateway
    • Money
    • Null Object
    • Strategy
    • Composite
    • Command
    • Template View
    • Query Object
    • Specification
    • Domain Model
    • Separated Interface
  • Design Principles
    • Single Responsibility
    • Open Closed principle
    • Dependency Inversion Principle
    • Hollywood principle
    • Tell Don’t Ask

I am sure I am missing lots in the description above, but you get the general idea. The important thing to note, is that all of the code (except for the changes I am making this week) was driven out through the course of the one week bootcamp!!

I am going to spend a couple of days ensuring that it contains as much code as possible for an initial drop, with full end to end functionality in place.

Going forward, this code will serve as a good place for me to be able to demonstrate in a public arena, concepts that people email me and ask me questions about. This way, I won’t have to spend as much time blogging, people can send me a question about something they are having problems with, I can implement the solution in the codebase and they can see how I attacked the problem from a test first perspective.

I envision this as being a very organic application. I am going to use it as a public tool to share whatever knowledge I have with as many people as possible.

When I post the code I will make sure I post a little about the application and why I feel that it will serve as a good tool to both teach and practice.

Comments [8] | | # 
 Monday, October 15, 2007
Monday, October 15, 2007 5:50:32 AM (Mountain Standard Time, UTC-07:00) ( Patterns | Programming )

Now I am by no means claiming to be any sort of patterns naming authority, but after you see the same occurent pattern in your applications you often will try to formulate some sort of vocabulary among the team to express the concept that you see occurring over and over again. This is the very nature of how patterns popped up in the first place. This is a pet name that I have come up with for the “recurring” theme you will see demonstrated here. If you are not familiar with the Gateway pattern check out the definition here.

I am going to demonstrate this pattern with an example that most people should have in place at the beginning of a project. Logging.

One of the things about Logging, is that it should be simple. Let’s assume that to get things rolling I really only care about logging informational messages. Assume I have a Calculator class that wants to do some logging, here are some possible code fragments that demonstrate the calculator class taking advantage of logging capabilities:

    public class Calculator
    {
        private ILog log;

        public Calculator(ILog log)
        {
            this.log = log;
        }

        public int Add(int number1,int number2)
        {
            log.InformationalMessage("About to add two numbers");
            return number1 + number2;
        }
    }

In this scenario the calculator is constructed with a log which will take care of logging behaviour on its behalf. I don’t like this as Logging falls under that set of “cross-cutting” concerns, and I don’t want to have to provide all of the objects in my application (domain layer or not) with this extra dependency. Here is another option:

public class Calculator { private ILog log; public Calculator() { } public ILog Log { set { this.log = value; } } public int Add(int number1,int number2) { log.InformationalMessage("About to add two numbers");
return number1 + number2; } }

Again, this is not optimal as it clutters up my object with unecessary noise. From a simplicity perspective, is it simpe for me to specify that “all objects should have a field of type ILog if they want to consume logging functionality? I think that the simplest api would be something like this:

public class Calculator { public int Add(int number1,int number2) { Log.InformationalMessage("About to add two numbers");
return number1 + number2; } }

Right now someone somewhere is screaming about the fact that I just introduced, what looks like, a Singleton. From an API perspective, the line above imposes the least design restrictions on my classes that want to consume logging functionality. The only caveat is that any class that wants to leverage logging is now coupled to the Log class. IMHO this is only an issue if it decreases the ability for me to test or if it decreases the option for me to swap out logging implementations (ex. Log4Net, MS Logging etc).

By the looks of the code above, it would seem that I have pinned myself into a fairly rigid design. I am not going to focus on how I test drive this out, but taking the API above, how could I go about testing the Log class?

With the Static Gateway pattern, the Gateway (in this case the Log class) does not actually do any of the work. It just serves as the entry point to the functionality. If that is the case here is a cut at what the Log class could look like:

public class Log { private static ILogFactory logFactory; public static void InitializeLogFactory(ILogFactory logFactory) { Log.logFactory = logFactory; } public void InformationalMessage(string informationalMessage) { logFactory.Create().InformationalMessage(informationalMessage); } } public interface ILogFactory { ILog Create(); } public interface ILog { void InformationalMessage(string message); }

How could you go about testing this class (I am demonstrating test-after, though the end solution was driven out test first). Here are two tests that prove out the functionality of the log class:

 

[Test] public void Factory_should_be_leveraged_to_create_logger() { MockRepository mockery = new MockRepository(); ILogFactory mockLogFactory = mockery.DynamicMock<ILogFactory>(); ILog mockLog = mockery.DynamicMock<ILog>(); using (mockery.Record()) { Expect.Call(mockLogFactory.Create()).Return(mockLog); } Log.InitializeLogFactory(mockLogFactory); using (mockery.Playback()) { Log.InformationalMessage("blah"); } Log.InitializeLogFactory(null); } [Test] public void Informational_message_call_should_be_delegated_to_created_logger() { MockRepository mockery = new MockRepository(); ILogFactory mockLogFactory = mockery.DynamicMock<ILogFactory>(); ILog mockLog = mockery.DynamicMock<ILog>(); using (mockery.Record()) { SetupResult.For(mockLogFactory.Create()).Return(mockLog); mockLog.InformationalMessage("blah"); } Log.InitializeLogFactory(mockLogFactory); using (mockery.Playback()) { Log.InformationalMessage("blah"); } Log.InitializeLogFactory(null); }

As you can see, these are completely interaction based tests (hence the lack of assertions). I broke up the test for leveraging the factory to create the logger and the delegation to the actual logger into 2 separate tests. I am also using the SetupResult vs Expect in the second test to indicate that, it is not the behaviour I care about testing. It just needs to be there to focus on what I actually care about, the delegation of the Log class to the created ILog implementation (which is currently a mock itself).

The nice thing about this scenario is that neither the Log class, or the clients of the Log class are aware/tied to any one particular ILog implementation. As long as I can prove out the correct interaction between the Log class and it’s dependency, I should be able to swap in any implementation of ILogFactory and the Log class is none the wiser.

The only downside to the current implementation of the Log class is the need for the static field and static method to initialize that field. Outside of introducing other concepts too early, the initialization of the Log class with an ILogFactory implementation is something that can be done at application startup. It is very likely that is should be one of the first things that should happen, as many other objects in the system may rely on the functionality of the Log class.

The only problem with the current solution is that the Log class is coupled to any changes that may occur in the ILog interface. To ensure that the ILog interface can vary independently of the Log class, I am going to make a small change to the API. Instead of calling methods on Log directly. I am going to change Log, and ILogFactory to the following:

public class Log { private static ILogFactory logFactory; public static void InitializeLogFactory(ILogFactory logFactory) { Log.logFactory = logFactory; } public static ILog For(Type type) { return logFactory.CreateFor(type); } public static ILog For(object itemThatRequiresLoggingServices) { return For(itemThatRequiresLoggingServices.GetType()); } }

The nice thing about this change is that now the Log class does not need to have a mirroring method for every method that may exist on the ILog interface. The ILog interface is now free to change independently of the Log class. Which means I could easily add methods to log with a specific logging level, etc. The Log class is now strictly a “Static Gateway” to Logging functionality.

I'll finish up by making a call into this API from the Calculator class: 

public class Calculator { public int Add(int number1,int number2) { Log.For(this).InformationalMessage("About to add 2 numbers"); return number1 + number2; } }

At this point the Calculator class is completely oblivious to the fact that there is currently no concrete ILogFactory/ILog implementation. It just cares about leveraging the Logging gateways “Static” method to have it log on its behalf. When we actually swap in a real ILogFactory & ILog, neither the Calculator or Log class will have to change at all.

In completion here is a quick implementation of an ILogFactory/ILog pair that will output log messages to the console (I’ll leave it up to you to come up with a more testable implementation of the following 2 classes):

public class ConsoleLogFactory : ILogFactory { public ILog CreateFor(Type type) { return new ConsoleLogger(); } private class ConsoleLogger : ILog { public void InformationalMessage(string message) { System.Console.Out.WriteLine(message); } } }

If you were to run the application now (after initializing the Log class with this ILogFactory implementation), you would see messages output to the Console, whenever the Add method on Calcuator was invoked.

In my next post, I’ll demonstrate how to leverage the Static Gateway pattern with respect to an IOC gateway, that will allow me to remove the static field and initilization method on the Log class.

Comments [7] | | # 
 Friday, October 12, 2007
Friday, October 12, 2007 8:52:36 AM (Mountain Standard Time, UTC-07:00) ( General | Programming )

I received this question a couple of days ago that I thought I would quickly take the time to respond to a question:

“At work over the past few weeks we’ve been watching your patterns talks on dnrTV.  We’ve found them really enlightening (we’re implementing some of them as I write this), but what has really amazed some of us is your use of ReSharper.  We have a printout of the default keymap for ReSharper, but we notice that you do some things using the keyboard that we would love to be able to do (and, in fact, didn’t even know were options in ReSharper).  One co-worker surmises that you have mapped your own keyboard shortcuts.  Is this the case, or are you just very knowledgeable of all of the shortcuts that ReSharper provides out of the box.  Either way, do you have any sort of keyboard mapping that you would be willing to share?  We’re always looking into ways to be better  - and what better way than to have a tool do all of the heavy lifting for you!!”

 

Here is the trick to getting really proficient with not just ReSharper, but also any and every program that windows throws at you. Start using the ALT key more!! With respect to the stuff that I am doing in ReSharper, let me confess that I have not mapped any extra keybinding other than the ones that come out of the box during the install.. Since 1.0 of ReSharper I have been leveraging , and will continue to use, the IntelliJ keyboard mappings. Before you can start leveraging the ALT key more effectively with ReSharper there is one thing you will have to do (you don’t have to, but it will save you an extra “R” in the keyboard sequences). If you are using VS2005 and you have both Refactor and ReSharper menu items (the Refactor menu is provided by the default install of VS2005, and will only show up if you are in a code file) you will need to remove the Refactor menu from your toolbar. If you want to get rid of it for good follow these steps:

 

  • Right click on the toolbar in VS and choose customize
  • Select the Commands tab
  • Click the Rearrange commands button
  • Ensure that the Menu Bar option is selected and choose the Refactor menu from the drop down list.
  • The Controls list should now be populated with all of the Refactor menu items.
  • Highlight the first item in the Controls list and hit ALT- D (delete).
  • Take care when deleting the last item as the list will automatically populate with the next set of controls from another menu item that you may not want to delete.
  • Click the close button on the dialog, and click the close button on the main dialog.
  • Voila, the Refactor menu item should be gone from your toolbar!!

Here are a couple of ReSharper key sequences that I use all of the time (I’ll leave it up to you to experiment):

  • ALT -> R -> N -> Enter – Create new class from file template template. This works because the first template in my list is the class template.
  • ALT -> R -> N -> I – Create new interface from file template.
  • ALT -> R -> N -> F – Create new TestFixture from file template
  • ALT -> R -> N -> M – Create new MockTestFixture from file template
  • ALT -> R -> W -> D – Bring up the TODO exlorer
  • ALT -> R -> O – Bring up ReSharper options
  •  

With respect to the TestFixture and MockTestFixture files templates, these are just one of many custom file templates that I use to help me get off the ground faster. I leverage ReSharper file templates a lot as it helps me start with code files that are much leaner than the studio counterparts.

 

Using the ALT key more will allow you to drop the mouse more than you think and start leveraging features directly from the keyboard.

 

Develop with Passion!!

 

 

Comments [2] | | # 
 Wednesday, October 10, 2007
Wednesday, October 10, 2007 8:14:51 AM (Mountain Standard Time, UTC-07:00) ( Programming )

I see lots of code bases throwing IList<T>, List<T> etc all over the place when half of the time all they really need is to return a set that can be either databound, or walked over and processed one at a time. For the scenarios where you don’t need to count the number of items or much of the other functionality that is exposed by the IList<T> interface, you can start to leverage the yield keyword more to tighten up the code.

Here is a common example, a service layer method call that returns a list of DTO’s that can be consumed by some sort of binding target. Assume that you are mapping domain objects into DTO’s to be consumed by the upper level layer (which could then be mapped into a presentation model). Let’s also assume that you have the following

  • Customer Domain Class
  • CustomerDTO Class
  • ICustomerDTOMapper interface (implementation knows how to map from domain to dto).
  • ICustomerRepository – repository interface to find customers
  • CustomerTask – service layer class

Here is the CustomerTask class with its appropriate dependencies injected, and the existing GetAllCustomers method using the temporary list:

 

public interface ICustomerDTOMapper { CustomerDTO MapFrom(Customer customer); } public interface ICustomerRepository { IEnumerable<Customer> All(); } public class CustomerTask { private ICustomerRepository customerRepository; private ICustomerDTOMapper customerDTOMapper; public CustomerTask(ICustomerRepository customerRepository,ICustomerDTOMapper customerDTOMapper) { this.customerRepository = customerRepository; this.customerDTOMapper = customerDTOMapper; } public IEnumerable<CustomerDTO> GetAllCustomers() { IList<Customer> results = new List<Customer>(); foreach (Customer customer in customerRepository.All()) { results.Add(customerDTOMapper.MapFrom(customer)); } return results; } }

With a  small change the code in the GetAllCustomers method can be changed to the  following:

public IEnumerable<CustomerDTO> GetAllCustomers() { foreach (Customer customer in customerRepository.All()) { yield return customerDTOMapper.MapFrom(customer); } }

This is a small change, but handy nontheless. Again, this is not new information, I just think that more people could start taking advantage of yielding in more situations where full blown lists are not called for.

Comments [5] | | # 
 Friday, September 28, 2007
Friday, September 28, 2007 1:12:49 PM (Mountain Standard Time, UTC-07:00) ( Patterns | Programming )

I am going to be posting a small sample that demonstrates what I was talking about in my post describing using Screen Bound DTO’s Presentation Model.

In chatting with a couple of people, they correctly fixed my terminology to use lingo that most people have already got a cursory knowledge of. So with that said, the technique that I described with regards to objects that are designed specific to the screens that they are servicing is the concept of a Presentation Model. DTO’s are still in the picture with respect to the messaging that can occur between presenter and service (and vice versa). The presentation model is their to satisfy the needs of the UI, be if for databinding or other UI needs (such as coloring for rows in a grid, highlighting customers with bad credit etc).

Ok, now we are all on the same page.

 

Comments [0] | | # 
 Thursday, September 27, 2007
Thursday, September 27, 2007 9:33:52 AM (Mountain Standard Time, UTC-07:00) ( Programming )

Currently, in a lot of the projects that I work on I tend to take a top down approach to development. Which means that I will start at test that focus on the presentation layer of the application.

Some people are curious as to this approach. My answer for this is simple. From the customers perspective, the first and simplest entry point to the application is the UI of the application itself. The UI also happens to be the place where developers spend a lot of their time, as that is often the place of most contention because of user expectations for how the UI should behave. By focusing on presenters and their accompanying view implementations, I can focus on stubbing out the behavior of the required service layer pieces as well as the accompanying Screen Bound DTOS that are required to present data to the particular user interface.

The concept of Screen Bound DTOS is probably not a new one, but one that I have been able to use with lots of success. Most people who look at my code are probably aware that I favour the use of DTOS with regards to use in the presenter to service layer communication as well as for displaying data in the UI. This is because you can build DTOS specific to the screens that they are going to service. They are completely separate from the underlying domain layer that will ultimately handle the business logic, and therefore are completely unaffected when a change to the domain model actually occurs. When a domain object or set of domain objects that ultimately map to a DTO change, the only thing that needs to change is the mapping from domain to the DTO. This ultimately allows my domain to evolve completely independently of the needs of the user interface.

Also keep in mind that a given screen may have the concept of more than one type of DTO for the different behaviours that can occur. For example, when I am displaying a list of products to purchase in an online store, I may have the need for a DTO that consists of the name, description, and price, as well as the SKU number for the product. When it comes time to add an item to my cart, what are the pieces of information that are really relevant to pass to the service layer? Only the SKU and the number that I want to add. I can encapsulate this information in an AddItemToCartDTO that contains the sku of the product and the quantity to be added. This DTO is free of all of the extra noise that existed in the previous DTO that is not necessary for the add to cart behavior

With regards to the presenter to service layer communication, these DTOs become essentially stripped down commands without the behaviour necessary to complete the task.

Using this technique and Top Down Development, I can completely finish off a screen, hand it off to the user to verify that it works the way that they want. I can do this by stubbing out service layer implementations to return fake data.

Once I get sign off from the user that the screen is up to par, I can now switch down to another layer and repeat the process of Top Down Development, from a different layer in the application.

 

Comments [9] | | # 
 Tuesday, September 04, 2007
Tuesday, September 04, 2007 10:20:09 AM (Mountain Standard Time, UTC-07:00) ( Programming )

During the DevTeach seminar that occured in Montreal in May I got an awesome opportunity to pair deliver a TDD workshop with Scott Bellware. One of the things he got me hooked on was using natural sentences as a test naming convention. So instead of this:

ShouldBeAbleToTransferFundsBetweenAccounts

You write it out like this:

Should be able to transfer funds between accounts.

Of course, only one of these is legitimate from a compilation perspective. So Scott had written a macro that would replace all of the spaces in the test name with underscore. You invoked it by highlighting the name of the test and hitting a key combination that was bound to the macro. Which would convert the natural sentence to the following:

Should_be_able_to_transfer_funds_between_accounts.

During the last course, Terry Hughes improved upon the macro so that now all I have to do is type out the name of the test and hit ALT + _ (that is what I have the macro bound to). I don’t need to select the name of the test.

It is a subtle change, but one that allows me to just write out the name of my test without worrying about camel casing or underscores.

Here is the macro:

 

Imports System Imports EnvDTE Imports EnvDTE80 Imports System.Diagnostics Public Module CodeEditor Sub ReplaceSpacesInTestNameWithUnderscores() If DTE.ActiveDocument Is Nothing Then Return Dim selection As TextSelection = CType(DTE.ActiveDocument.Selection(), EnvDTE.TextSelection) selection.SelectLine() If selection.Text = "" Then Return Dim prefix As String = "public void " Dim index As Integer = selection.Text.IndexOf(prefix) prefix = selection.Text.Substring(0, index) + prefix Dim description As String = selection.Text.Replace(prefix, String.Empty) selection.Text = prefix + description.Replace(" ", "_").Replace("'", "_") selection.LineDown() selection.EndOfLine() End Sub End Module

This video shows the macro in action.

 

Enjoy

Comments [8] | | # 
 Monday, June 25, 2007
Monday, June 25, 2007 3:52:19 PM (Mountain Standard Time, UTC-07:00) ( .Net 2.0 | .Net 3.0 | Agile | C Sharp | Patterns | Programming | Training )

That’s right folks. Nothin But .Net is coming to New York.

The course is going to be held at TCCIT Solutions.

 The course runs for the week of October 22nd – 26th, 2007.

Overview

Nothin But .Net is a five day boot camp that will focus on pragmatically applying .Net within the context of developing a working N-Tiered application. Registrants will learn about advanced features of .Net (2.0/3.0) as they are applied to the task of building a complete application from the UI layer all the way down to the mapping layer.

WARNING!!!!

If you are expecting to come to this course to learn about how to have VS.Net automatically generate an “application” for you, then this course is NOT for you.

This course is all about taking control of the .Net framework and having it work the way you want. This course will place a heavy emphasis on getting back to the basics and making .Net do things the way you want it to, in a predictable and testable way.

This course will focus on a code centric view of application development vs. the typical databinding/designer magic covered by many typical .Net courses. You will walk away with a deep understanding of fundamental aspects of .Net and how these pieces can be used to develop and deliver enterprise scale applications.

Core Concepts Overview

  • Expanding the capabilities of developing with VS.Net - Enter ReSharper (a productivity add-in for Visual Studio .Net)
  • There’s more to life than generated code
  • Automation for the developer
  • Generics ( they’re not just for collections )
  • Back to basics - Rules Of Good Object Oriented Design
  • Dependency Injection
  • Object Relational Mapping in .Net
  • Applying the dependency inversion principle
  • Domain Driven Design
  • Passive View/Supervising Controller (Model View Presenter)
  • Creating layered architectures
  • Driving out functionality and design through testing
  • Taking Control Of Databinding
  • Behavior (Test) Driven Development
  • Core design patterns applied
  • Pragmatic Productivity Tools For Developers

Although the list may look rather daunting, the majority of the bullet points will be covered during the evolutionary design and construction of the sample project.

One of the main goals of the course is to show how to effectively use behavior (test) driven development, design patterns and a solid toolset to develop a portion of a non-trivial application.

The course will allow students to pragmatically apply BDD practices as well as teach people how to utilize fundamental OO concepts and techniques that will allow for them to have cleaner, more loosely coupled architectures. It will also be an opportunity for students to see what is involved in creating applications that utilize a Rich Domain Model,and the supporting infrastructure that is required to use "Plain Old Objects".

I have successfully delivered this course several times with great success. I anticipate that people who are interested will find that this is a very unique course offering, not typical of what is being delivered in the mainstream.

Seats are limited. The course costs $3000/US for a full 5 days. The fee covers:

  • 5 (8 - 14 hour days, depending on the audience availability) of bootcamp style instruction
  • Breakfast
  • Hot Lunch
  • Book - Patterns Of Application Architecture
  • Software – ReSharper 3.0 License

If you have any questions please don't hesitate to contact me at jp@jpboodhoo.com.

To Register for the course please use the following link:

Comments [2] | | # 
 Wednesday, June 13, 2007
Wednesday, June 13, 2007 12:52:55 PM (Mountain Standard Time, UTC-07:00) ( Programming )

Scott Hanselman posted about six essential language agnostic programming books. I agree on not being bound to one language. Currently my most used language is C#.

A while ago I created an Amazon listmania called Building a Solid Core, that focuses on a bunch of language agnostic books mixed in with some killer C# books.

Check it out here, as I feel that all of the titles on the list are essential reading.

Comments [0] | | # 
 Monday, May 14, 2007
Monday, May 14, 2007 7:03:34 AM (Mountain Standard Time, UTC-07:00) ( Programming )

Got a great email this morning from Brian Di Croce that I thought I would share with everyone.

In Exodus 18 we read how Moses overextended himself in caring for the people.  His father-in-law, Jethro, asked him why he sat alone from morning until night with the people standing around him.  He responded  that the people came to him to inquire of the Lord and that he judged between them that they might know God's laws and statues.

Here comes the principle of separation of responsibilities...

Jethro told him that he (Moses) would wear himself out, as well as the people he was trying to help.  He told him that the responsibility was too heavy , and warned him that he could not continue to bear it alone.  Then he proceeded to give his son-in-law some wise advice.  He explained how to delegate responsibility.

For any of you interested; here is the actual story taken directly from Exodus 18: 23–23 (NIV version):

The next day Moses took his seat to server as judge for the people, and they stood around him from morning till evening. When his father-in-law saw all that Moses was doing for the people, he said, “What is this you are doing for the people? Why do you alone sit as judge, while all these people stand around you from morning till evening?”

Moses answered him, “Because the people come to me to seek God’s will. Whenever they have a dispute, it is brought to me, and I decide between the parties and inform them of God’s decrees and laws.”

Moses father-in-law replied, “What you are doing is not good. You and these people who come to you will only wear yourselves out. The work is too heavy for you; you cannot handle it alone. Listen now to me and I will give you some advice, and may God be with you. You must be the people’s representative before God and bring their disputes to him. Teach them the decrees and laws, and show them the way to live and the duties they are to perform. But select capable men from all the people– men who fear God, trustworthy men who hate dishonest gain – and appoint them as officials over thousands, hundreds, fifties and tens. Have them serve as judges for the people at all times, but have them bring every difficult case to you; the simple cases they can decide themselves. That will make your load lighter, because the will share it with you. If you do this and God so commands, you will be able to stand the strain, and all these people will go home satisfied.”

 

Interesting thought to start the week out with!!

 

God Bless.

Comments [2] | | # 
 Friday, April 20, 2007
Friday, April 20, 2007 7:25:26 AM (Mountain Standard Time, UTC-07:00) ( Programming )

Having seen what Justice is upto, I thought I would take the time to answer a question that I get asked all the time “What’s books do you recommend I should read”?

While the scope of the books I could recommend is quite large, I am going to narrow my focus to the realm of the developer. Some of these books are ones that I wish I had read while I was still in school (of course, they might not have been out then!!). The list is ordered in the way “I feel” they should be read. More specifically, I have focused on books that I think can equip people (alongside real world experience) to “Build A Solid Core”

Here it is:

You’ll notice that I have not even touched on specialized topics such as web/windows development,object relational mapping, or even sql. We’ll save that list for another day. I have also published this as a listmania list to Amazon.

Happy Reading.

Comments [5] | | # 
 Tuesday, April 17, 2007
Tuesday, April 17, 2007 1:35:11 PM (Mountain Standard Time, UTC-07:00) ( C Sharp | Programming )

This morning had a good question asked:

Q: Basically we're writing the billing processing part of our business
application.  On the 1st and 15th of the month, we bill all our
policy holders and it's usually 10,000 or so transactions that need to
be run.  The processor gateway runs as a webservice.  Now since these
10,000 don't rely on each other at all, I figured to speed it up I
could run 10-20 at a time in a job.
 
So I wrote this simple class so far, but I'm not sure if it's even
close, it just takes a processing date, loads all the queued
transactions, and sends them into the authorize and payment manager.
It seems that async threads you have to delegate to a void
parameterless method, so I built a locked incrementer for the index on
the generic list of transactions and try to process them like that.
It's the while loop stuff that is lame, I'd really like it to just
spawn X number of threads where X is configurable.  Maybe I just dont'
get it, here's the code though: 

public class Billing { public Billing(DateTime ProcessDate) { _ProcessDate = ProcessDate; PopulateTransactions(); ExecuteBilling(); } private Int32 _TransactionIndex = 0; private List<Transaction _TransactionsToBill; private DateTime _ProcessDate; private void PopulateTransactions() { _TransactionsToBill = TransactionManager.GetQueuedTransactions(_ProcessDate); } private void ExecuteBilling() { do { Thread t1 = new Thread(new ThreadStart(ProcessTransaction)); t1.Start(); Thread t2 = new Thread(new ThreadStart(ProcessTransaction)); t2.Start(); Thread t3 = new Thread(new ThreadStart(ProcessTransaction)); t3.Start(); Thread t4 = new Thread(new ThreadStart(ProcessTransaction)); t4.Start(); Thread t5 = new Thread(new ThreadStart(ProcessTransaction)); t5.Start(); } while (_TransactionIndex < _TransactionsToBill.Count); } private void ProcessTransaction() { string Message; Transaction transaction = GetNextTransaction(); if (transaction != null) CyberSourceManager.AuthorizeAndCapture(transaction.InvoiceID,transaction.ID, out Message); } private Transaction GetNextTransaction() { Interlocked.Increment(ref _TransactionIndex); if (_TransactionsToBill.Count _TransactionIndex) { return _TransactionsToBill[_TransactionIndex - 1]; } return null; } }

A: The main problem that you are concerned about is : “I'd really like it to just spawn X number of threads where X is configurable”. The following code is another alternative implemented using the Monitor class to create a producer/consumer queue:

public class Billing { private Queue<Transaction> transactionQueue; private IList<Thread> workerThreads; private object mutex; public Billing(int numberOfWorkerThreadsToUse,IEnumerable<Transaction> itemsToProcess) { mutex = new object(); workerThreads = new List<Thread>(); transactionQueue = new Queue<Transaction>(); InitializeConsumers(numberOfWorkerThreadsToUse); QueueUp(itemsToProcess); QueueEmptyTransactionsForEachActiveThread(); } private void QueueUp(IEnumerable<Transaction> toProcess) { foreach (Transaction transaction in toProcess) { QueueForProcessing(transaction); } } private void QueueEmptyTransactionsForEachActiveThread() { foreach (Thread wokerThread in workerThreads) { QueueForProcessing(null); } } private void QueueForProcessing(Transaction transaction) { lock (mutex) { transactionQueue.Enqueue(transaction); Monitor.PulseAll(mutex); } } private void InitializeConsumers(int numberToInitialize) { for (int i = 0; i < numberToInitialize; i++) { Thread thread = new Thread(ProcessTransactions); workerThreads.Add(thread); thread.Start(); } } private void ProcessTransactions() { while (true) { Transaction transaction = null; lock (mutex) { while (transactionQueue.Count == 0) Monitor.Wait(mutex); transaction = transactionQueue.Dequeue(); } if (transaction == null) return; Process(transaction); } } private void Process(Transaction transaction) { //Do you work here } }

The advantage of this code over the prior code is it mitigates unecessary allocation of an unknown number of threads and opts for the creation of an explicit “known” number of worker threads that will process items on the queue. This code leverages the ability to wait on a locked object. When a transaction is Queued up, Monitor.PulseAll is invoked (on the mutex) to wake up all threads that may already be waiting on that mutex,based on which thread is currently highest in the lock queue, it will be able to Dequeue a single transaction from the “transaction” queue and process it.

The constructor for the Billing class allows you to specify how many worker threads should be created. You should notice, that the Consumer threads can start immediately processing Transactions the second a Transaction is queued for processing. This has the benefit of not needing to have the queue populated in its entirety before processing. As new items are added to the queue, a worker thread can pick it up and process it. Once all of the real transactions have been added to the queue for processing, a “null” transaction is placed onto the queue for each worker thread that was created. This ensures that each thread will actually terminate.

Notice how in the ProcessTransactions method, it does not stop processing if the number of items in the queue == 0. This is because (again, multi threaded coding is hard) since items are being added to the queue from a separate thread, and items are being processed by 1 of the many worker threads, the client thread may not have had the opportunity to place items on the queue before the (transactionQueue.Count == 0) condition is evaluated. If I used the count of the items in the queue as my termination condition, the worker thread would most likely terminate too early. Hence the need for the null transaction that each thread will have to handle. Once the worker dequeues a null transaction, it knows that it is time for it to finish.

I’m not saying this is the only way to solve this problem, I just wanted to demonstrate how you could share the load of the processing between a finite amount of worker threads, while utilizing the Monitor class to perform fine grained synchronization.

The usage for this class becomes very simple:

new Billing(5,transactionService.GetTransactionsToProcess());

 

 

Comments [2] | | # 
 Monday, April 16, 2007
Monday, April 16, 2007 9:11:37 AM (Mountain Standard Time, UTC-07:00) ( Programming )

Just started a new contract and got thrown into a world that I have relatively “no” experience in. The world of data warehouses, cubes, analysis services, SSIS.

Anyway, not having a good handle on some of this stuff I needed to get an understanding of how some of the pieces all fit together.  Never one to be too proud to ask for help, I turned to a good friend and awesome teacher who gave up a good couple of hours in his day to school me in all things OLAP centric!!

It’s times like this when I am reminded of the importance of why we all got into this profession in the first place. The mind stretch!!!! I don’t love the designer centric world of the tools that I am going to be having to use for the next couple of weeks, but they are the means to a quick end for a reporting deliverable that needs to be shot out the door. It’s also a chance to play around with a set of tools that are outside of the realm of tools that I usually develop with. Which ultimately will make me a more rounded devleoper (seems weird to call it development when there is little coding that actually goes on…).

On the topic of learning new things; in the past I have tried to follow the guidance of the Pragmatic Programmer and taken it upon myself to learn at least one new language a year for the last couple of years. Each year I bring a couple of new dev tools into the mix (usually open source). And each project, I try to force myself to think of different ways to solve problems that may be similar to ones I have already encountered.  Because of the set of tools, practices, and techniques I have been focused on over the last couple of years, I think I  became a little closed to the MS specific toolsets that were coming onto the market. Can you believe I’ve never even looked at the Analysis Services, and SSIS projects inside of studio before!! My personal experience has been that for most jobs I want to tackle, there are much more lightweight alternatives that do the job for me, than what has typically come out of the MS space.

Back to the “learning” thing, I think about times when I am asked  “How do you keep up with it all?”, I answer them simply – “I don’t”. I keep up with the things that have a direct impact on the projects that I am currently working on, and I keep my eyes peeled so I have a cursory knowledge of stuff coming down the pipe. Of all of the stuff that has come down the firehose in the last couple of months, the stuff that I am currently focused on (ie. actively working with) is:

  • Windows Communication Foundation
  • Windows Presentation Foundation

Wait JP, that’s it? That’s right. All of the other stuff I currently use, works and it works well for me on 90% of the projects that I have been presented with. It also allows me to narrow my focus on 2 new technologies that I want to learn really well, as opposed to being spread too thin trying to learn several tools not so well. This will once again augment my regular toolset, that usually consists of a large combination of open source tools, MS offerings, and a smattering of well deserved purchased tools that do a lot of heavy lifting for me.

My personal recommendation with regards to personal learning is to first and foremost focus on “building a solid core” which can be leveraged now and in the future to distill which technologies, practices, and tools can aid you on projects you are working with, as well as having a foundation that allows you to learn new tools and frameworks fairly quickly. Also, focus on being able to “filter” out the noise that is not currently part of your current “conversation”. This leaves you free to focus on the tasks at hand with the tools you know while simultaneously logging in your mind stuff that you could see benefit applying on future tasks.

Happy Learning.

 

 

Comments [2] | | # 
 Tuesday, April 10, 2007
Tuesday, April 10, 2007 11:42:17 AM (Mountain Standard Time, UTC-07:00) ( Programming )

A couple of good comments came up in the last post about the use of utility classes in the realm of SRP. I made the statement that I personally don’t mind using utility classes sparingly, as long as the class itself is adhering to the rules of SRP, meaning that the methods it is composed of revolve around one discrete area of functionality.

Ayende brought up a good code example and asked Jeff how he would handle the situation without using utility classes (Jeff posted a response to this question). This is the code that Ayende provided:

public void QueueToExecute(ICommand command)
{

  Validation.NotNull(command,
"command");

 
// do stuff
}

For those not familiar, the check that is being performed to ensure that the command is not null could be viewed as a simple validation check. Some developers refer to this as more than simple validation checking and refer to it as DBC (Design By Contract). Intentional or not, the explicit checking of the “non null precondition” is a DBC technique, used to indicate to the client developer preconditions that must be in place for the method to continue, I digress!!

So what does OCP have to do with any of the code that was talked about the other day? Looking at the code above, I could make an assumption that the method lives on some sort of ICommandQueue implementation (we’ll call it CommandQueue). And it could look something like this (lots omitted for brevity):

public class CommandQueue : ICommandQueue { private Queue<ICommand> commands; public CommandQueue() : this(new Queue<ICommand>()) { } public CommandQueue(IEnumerable<ICommand> initialSetToQueue) { commands = new Queue<ICommand>(initialSetToQueue); } public void QueueToExecute(ICommand command) { commands.Enqueue(command); } }

Notice that the current version of CommandQueue does not contain the check for nulls on the QueueToExecute method. I could leverage DBC to ensure that preconditions expected by the client are met before adding the Command to the queue. This results in the call to the utility Validation class that Ayende brought in earlier:

public void QueueToExecute(ICommand command) { Validation.NotNull(command,"command"); commands.Enqueue(command); }
 

This works. If the Validation class is simply a static container for procedural methods the NotNull method could look as follows:

public class Validation { public static void NotNull(object item,string itemDescription) { if (item == null) throw new ContractViolationException(itemDescription); } }

On the other hand, Validation could be a mere Gateway that provides convienient access to discrete Assertion objects etc. I could carry on but I would rather focus on the current consumer of the Validation class itself. The CommandQueue. In the original implementation of CommandQueue, it had no smarts about performing the null check on incoming commands. By introducing the explicit check in the QueueToExecute method I have satisfied a rule that needed to be encapsulated for the method, but in the process I have violated the Open Closed Principle.

The Open Closed Principle

“a class should be Open for extension but Closed for modification”.

Back to the CommandQueue example, the original CommandQueue implementation worked fine before the requirement came along that said that it should ensure that incoming commands are not null. If I wanted to adhere to OCP, the “Closed” part of the principle states that I should not need to change my original implementation to deal with the new requirement. The “Open” part of the principle means that my design should allow me to add new behaviour to a CommandQueue without needing to go in and actually change the code of the original CommandQueue implementation. There are a couple of ways I could accomplish this and still adhere to OCP. For now, I’ll use a Proxy to ensure that commands coming in cannot be null:

public class NullRejectingCommandQueue : ICommandQueue { private ICommandQueue queueToProxy; public NullRejectingCommandQueue(ICommandQueue queueToProxy) { this.queueToProxy = queueToProxy; } public void QueueToExecute(ICommand command) { Validation.NotNull(command,"command"); queueToProxy.QueueToExecute(command); } }

With this proxy in place, I can remove the validation check from the original CommandQueue, and I have extended it without changing it. In my service layer (or container preferably), I could ensure that all instances of CommandQueues get wrapped in the NullRejectingCommandQueue proxy so that the null check will be performed. Without bringing a container into the mix, I could use a factory to get instances of CommandQueues: 

public class CommandQueueFactory : ICommandQueueFactory { public ICommandQueue Create() { return new NullRejectingCommandQueue(new CommandQueue()); } }

Reality Check

I am hoping that most of you realize that this could very well be overkill for what you are trying to do. Part of evolving as a good designer is knowing when trying to adhere to a principle, or leverage a pattern can actually be detrimental to your code. What can help you answer that question? Time and practice. The first step in becoming a good designer, is being able to first identify the smells in your code. Just because you have a cold does not mean that everyone else can’t smell the fish in your garbage can. Once you are able to identify the code smells, before even looking at design patterns, you should get a good handle on some of the fundamental design principles that can lead you to cleaner OO designs (SRP and OCP being 2 of them).

Remember how I said that all of the design principles in one way or another tie back to SRP. In this example, performing the check for null commands was not an intended “responsibility” of the command queue class. It’s responsibility was to queue commands for execution. By adding the null check, we added added another responsibility to the CommandQueue class. I am not suggesting that the null check should not be there. I just wanted to demonstrate how you can extend the behaviour of an object (open it up with new responsibilities) without having to change the target object itself.

Comments [2] | | # 
 Monday, April 09, 2007
Monday, April 09, 2007 6:17:51 AM (Mountain Standard Time, UTC-07:00) ( Programming )

One of the things that has really been hitting me in the face lately is the importance of adhering as closely as possible to the Single Responsibility Principle.

SRP simply states that:

 “A class should have only one reason to change”.

On the surface this can be a very simple principle to grok, the reality is that ensuring that a class is doing only one thing can be a skill that developers will continue to evolve over the course of their career.

Most people have come across the term cohesion, which describes how well the different behaviors of an object work together to accomplish a common task. Cohesion and SRP are one in the same. When looking at any arbitrary class in your codebase, it can often be very easy to determine whether a class is breaking SRP:

  • A UI that performs direct DB manipulation as well as validation of data entry.
  • “Bucket” utility classes that do everything from sending email to performing string manipulation.

Each extra responsibility you add to a class gives it another reason to change. Instead of composing highly cohesive objects each with a discrete responsibility that can be orchestrated together to accomplish a common task, many people opt for the behavior bloat that often can result when the time to factor out discrete behaviors has been skipped.

In my experience over the last couple of years, when you have someone sitting beside you, making you question strongly as to whether a particular piece of behavior is being placed correctly, it will almost always help drive out more cohesive objects that are focused around a single responsibility. Not only does this make them more testable. It also shields the rest of the system from any changes that may come along in that component, as its set of behaviors are fixed around one particular piece of functionality.

Single Responsibility is what drives us to create object oriented systems, that also leverage layering schemes, to ensure that ,even at the logical layering level, a “layer” as a whole is adhering to SRP. This means that when I create a “Presentation” layer, the layer and any of its accompanying components are focused around presentation related behavior. A DAL will be focused solely around providing data access services to the rest of the application. The domain model will be focused around encapsulating the business rules, and the heart of the system.

When you look at your codebases, ask yourself some hard questions and see whether or not you are placing too much responsibility on one object, component, or layer. By striving to follow this principle more diligently you will foster and encourage practices that lead to more loosely coupled, highly cohesive systems. Ultimately, all of the principles and practices of good OO software design come back in one way or another to trying to follow this principle as closely as possible!!

Comments [0] | | # 
 Friday, April 06, 2007
Friday, April 06, 2007 8:06:08 PM (Mountain Standard Time, UTC-07:00) ( Programming )

Since I have just been added to the CodeBetter team, I am sure that there will be lots of people reading who are not familiar with my existing blog. I am going to be continuing to cross post, but I thought I would take the time to provide people with links to posts that I have received the most feedback for (or that I think are interesting). The following is a list of my readers favorite posts (and articles) since I started blogging back in December 2005. Enjoy:

Comments [1] | | #