Documenting my journey through the pratice of software development RSS 2.0
 Tuesday, July 15, 2008

In the last month or two, I have been hand coding a lot of mock and stub objects and it has become a nightmare to manage. My primary reason for doing this by hand was that Rhino Mocks 3.4 and older did not fit with the BDD style unit tests that I was writing. Yes, I made it work in a few places, but it was ugly and annoying.

Fortunately, Ayende has cleaned it all up with the new syntax and made it very easy to assert that individual expectations were met, with v3.5. I finally got around to trying out the new syntax today, and I immediately fell in love with it. For example:

[Concern("User Administration")]
public class When_accessing_the_system_as_a_non_administrator : ContextSpecification
{
    private IMainView view;
 
    private IMainView GetView()
    {
        IMainView mockView = MockRepository.GenerateMock<IMainView>();
        mockView.Expect(v => v.EnableUserManagement()).Repeat.Never();
        mockView.Expect(v => v.DisableUserManagement()).Repeat.Once();
        return mockView;
    }
 
    protected override void Context()
    {
        User administrator = new User();
        administrator.IsAdministrator = false;
        CurrentUser.User = administrator;
 
        view = GetView();
        new MainPresenter(view);
    }
 
    [Observation]
    public void Should_not_display_the_User_Management_option()
    {
        view.AssertWasNotCalled(v => v.EnableUserManagement());
    }
 
    [Observation]
    public void Should_hide_the_user_management_option()
    {
        view.AssertWasCalled(v => v.DisableUserManagement());
    }
 
}

In the "GetView" method, I am setting up two very distinct expectations on my mock object.

  1. Never Call the EnableUserManagement method.
  2. Call the DisableUserManagement method once.

With the new Rhino Mocks syntax, I can easily verify that each one of these expectations was called via my "should" observations.

The "AssertWasNotCalled" extension method verifies that an expectation of Repeat.Never was setup and that the method was not called.

mockView.AssertWasNotCalled(v => v.EnableUserManagement());

And the "AssertWasCalled" extension method verifies that the expectation was to call the method, and that the method actually was called.

mockView.AssertWasCalled(v => v.DisableUserManagement());

I like it. The new syntax has really simplified my Context Specification testing.

Tuesday, July 15, 2008 2:43:10 PM (Central Standard Time, UTC-06:00)  #    Comments [1]. Trackback 
Tags: .NET | Behavior Driven Development | Lambda Expressions | Rhino Mocks | Unit Testing | User Stories

 Monday, June 23, 2008

Over the weekend, I spent some time refactoring some business rules in my current project, to use the ISpecification<t> framework that I previously created.

One of my coworkers had asked about logical groupings - making sure that we can handle complex logic such as, "(this and this) or this". Since my project actually made use of logical groupings I wanted to share with the world and show how easy it is.

In this example, I have a Date Range that is being selected – a From date and a To date. The rules are as follows for validating the range:

  • If a From date and a To date are provided, the From date must be equal to, or before, the To date
  • Or, you can specify a From date without To date
  • Or, you can specify a To date without From date

The following is the actual code that I’m using to define these business rules, via the ISpecification<t> framework. 

PredicateSpec<ExtractSearchCriteria> fromDateProvided = new PredicateSpec<ExtractSearchCriteria>(crit => crit.FromDate > DateTime.MinValue);
PredicateSpec<ExtractSearchCriteria> toDateProvided = new PredicateSpec<ExtractSearchCriteria>(crit => crit.ToDate > DateTime.MinValue);
PredicateSpec<ExtractSearchCriteria> fromDateBeforeToDate = new PredicateSpec<ExtractSearchCriteria>(crit => crit.FromDate <= crit.ToDate);  
 
ISpecification<ExtractSearchCriteria> validDateRangeSpec =
    (
        (fromDateProvided.And(toDateProvided))
        .And(fromDateBeforeToDate)
    )
    .Or(
        fromDateProvided.Not(toDateProvided)
    )
    .Or(
        toDateProvided.Not(fromDateProvided)
    );

Here, I am defining the core of the business rules – to check if the From date was provided, to check if the To date was provided, and to check if the From date is before or equal to the To date. From these core specifications, I can build the aggregate spec that handles all of the stated rules for validating the date range.

There are three logical groupings using parenthesis to represent each of the business rules that can comprise a valid date range. The first logical grouping checks to see if both a From and To date are provided, and checks if the From date is before or equal to the To date, if both are provided.

(
    (fromDateProvided.And(toDateProvided))
    .And(fromDateBeforeToDate)
) 
 

The second group is specified with an Or, and checks to see if we provided a From date but not a To date.

.Or(
    fromDateProvided.Not(toDateProvided)
)

And the third group also uses an Or, and checks to see if we provided a To date but not a From date.

.Or(
    toDateProvided.Not(fromDateProvided)
)

The end result is that we have one of three possible ways for this date range to be valid – all logically grouped and relatively easy to read (compared to a bunch of if-then statements, at least). Even better – we re-used two out of three simple ISpecification<t> objects to create all of the rules for this validation check. This helps to create a validation that is not only easier to read, but easier to maintain and enhance in the future.

Monday, June 23, 2008 9:43:24 AM (Central Standard Time, UTC-06:00)  #    Comments [0]. Trackback 
Tags: .NET | Analysis and Design | Design Patterns | Lambda Expressions | Principles and Patterns | Refactoring

 Thursday, June 19, 2008

Inspired by my recent readings in Domain Driven Design - specifically Chapter 10, "Supple Design" - and recent posts by David Laribee and Nigel Sampson, in combination with the recent pains I've been putting myself through, trying to test query generation code in a search screen, I decided to spike out a quick example of a reusable Specification implementation.

Rather than repeat what's already been said, I'm just going to get straight to the code.

using System;
 
namespace Spec_Spike
{
    class Program
    {
        static void Main()
        {
        
            Foo foo1 = new Foo();
            foo1.Bar = "Test";
            
            ISpecification<Foo> equalSpec = new Specification<Foo>(foo => foo.Bar == "Test");
            ISpecification<Foo> notEqualSpec = new Specification<Foo>(foo => foo.Bar != "Not Equal To This Text");
            ISpecification<Foo> falseSpec = new Specification<Foo>(foo => false);
 
            ISpecification<Foo> passingSpec = equalSpec.And(notEqualSpec);
            ISpecification<Foo> failingSpec = passingSpec.And(falseSpec);
 
            Console.WriteLine(equalSpec.IsSatisfiedBy(foo1));
            Console.WriteLine(notEqualSpec.IsSatisfiedBy(foo1));
            Console.WriteLine(passingSpec.IsSatisfiedBy(foo1));
            Console.WriteLine(failingSpec.IsSatisfiedBy(foo1));
        }
        
    }
    
    public class Foo
    {
        public string Bar;
    }
    
    
    public interface ISpecification<t>
    {
        bool IsSatisfiedBy(t obj);
        ISpecification<t> And(ISpecification<t> lhs);
    }
    
    public class Specification<t>: ISpecification<t>
    {
        private readonly Predicate<t> _pred;
 
        public Specification(Predicate<t> pred)
        {
            _pred = pred;
        }
 
        protected Specification(){}
    
        public virtual bool IsSatisfiedBy(t obj)
        {
            return _pred(obj);
        }
 
        public ISpecification<t> And(ISpecification<t> andSpec)
        {
            return new AndSpecification<t>(this, andSpec);
        }
    }
    
    public class AndSpecification<t>: Specification<t>
    {
        private readonly ISpecification<t> _spec1;
        private readonly ISpecification<t> _spec;
 
        public AndSpecification(ISpecification<t> spec1, ISpecification<t> spec)
        {
            _spec1 = spec1;
            _spec = spec;
        }
 
        public override bool IsSatisfiedBy(t obj)
        {
            return (_spec.IsSatisfiedBy(obj) && _spec1.IsSatisfiedBy(obj));
        }
 
    }
    
}

Drop this code into a console app in C# 3.5 and watch the magic happen. Here's the output:

image

These are the results that I expected - the first 2 individual specs passed, the first combined spec passed, and the last combined spec failed.

Overall, I'm fairly excited about the possibilities here. I'm thinking that I may actually be able to properly unit test the query generating code in my search screen with this basic technique. I'm still not 100% sure on that, but I plan on trying, anyway.

For more information on the Specification pattern, I highly recommend you read the previously linked posts by David Laribee and Nigel Sampson, in addition to reading all of the Domain Driven Design Book. This is one of those books that should fundamentally change the way you think about software development.

Thursday, June 19, 2008 8:35:20 PM (Central Standard Time, UTC-06:00)  #    Comments [0]. Trackback 
Tags: .NET | Analysis and Design | Design Patterns | Domain Driven Design | Lambda Expressions | Principles and Patterns | Unit Testing

 Thursday, May 15, 2008

I've been toying around with various ideas in code, and I've come to the conclusion that the following formula is true:

Lambda Expressions + Func<> and Action<> = Easy Command Patterns

As a very contrived, quick example:

public class DoStuff
{
    private Func<CommandResult> Step1 { get; set; }
 
    private Func<CommandResult> Step2 { get; set; }
 
    public DoStuff(Func<CommandResult> step1, Func<CommandResult> step2)
    {
        Step1 = step1;
        Step2 = step2;
    }
 
    public void DoTheStuffProcessing()
    {
        CommandResult result = step1();
 
        if (result.Succeeded)
        {
            step2();
        }
    }
}

It's ... so ... beautiful ...

Thursday, May 15, 2008 2:00:34 PM (Central Standard Time, UTC-06:00)  #    Comments [0]. Trackback 
Tags: .NET | Lambda Expressions | Principles and Patterns

 Thursday, May 01, 2008

I hate the Try Catch syntax in C# - it's bulky, ugly, and makes my code hard to read.

try
{
  // do some stuff here
}
catch
{
  //handle exceptions here
}
finally
{
  //clean up here
}

Although very functional and well documented, to the point where it can be effectively used, I don't see the elegance that I want in my language - especially if you actually have to catch a specific exception and deal with it in the middle of your functional code.

So, I'll create the elegance that I want.

public class TryCatch
{
 
    public static Exception Do(Action action)
    {
        Exception caughtException = null;
        try
        {
            action();
        }
        catch(Exception ex)
        {
            caughtException = ex;
        }
        return caughtException;
    }
 
}

With this very basic implementation, using lambda expressions, I can create a much more friendly syntax to use:

Exception ex = TryCatch.Do(() => 
{
  //Do Stuff Here, with assurance that an exception will be caught, if thrown.
});
 
//send the exception off to the exception processing / handling, if needed.

From there, you could add a "fluent" interface to catch specific exceptions, have a finally block, etc - but you end up with the same ugliness that I wanted to avoid.

//Blech. This just puts us right back in ugly-ville
TryCatch.Do(() =>
{
    //throw exception here
}).Catch<Exception>(() =>
{
    //handle exception here
});

ugh - ugly, for that matter. That didn't help us at all. And we don't need it, anyway. You are guaranteed to have the before and after TryCatch.Do execute.

//setup
IDBConnection conn = GetMyConnection();
 
TryCatch.Do(() =>
{
    //execute
    conn.Open();
});
 
//cleanup
if (conn != null)
  conn.Dispose();

I like it.