October 2005 - Posts

She can't walk, but she sure can code!

Ok, so Bruce Tate has a real life code-monkey. So what! My daughter is only 14 months old and already she is following in her fathers footsteps. Today she had some real tricky enterprise architecture challenges to solve for a large honey manufacturer in the Hundred Acre Woods. She’s a bright kid, reaching straight for Martin Fowlers excellent signature series for reference. See for yourself.

If you’d like to geek-up on the same books my toddler is reading; check out these excellent books. They’re worth while reading, even if you’re an adult.

Martin Fowler's Patterns of Enterprise Architecture
Gregore Hophe's Enterprise Integration Patterns
Eric Evans' Domain Driven Design

Be sure to check out these children’s classics as well:

Mr. Bunny's Guide to ActiveX
Mr. Bunny's Big Cup o'Java.

C# 3.0 and the Spaceship Operator

Abhinaba has an interesting blog entry about my all time favorite operator; Ruby’s spaceship operator <=>. This operator is a comparison operator akin to .NET IComparable interface. A part from looking cool in the editor, the operator it self isn’t the reason for my interest in it. It is the power of combining the spaceship operator with Ruby’s Comparable which’s shows the true power of mixins. If a Ruby class implements the spaceship operator, you get the <, <=, ==, >= and > operators, as well as a between? method for free just by importing the Comparable mixin.
Abhinaba points out how much simpler operator overloading would be if C# supported the spaceship operator. I agree with him on this, but with C# 3.0 we'recloser to encounters of the third kind than you might think. Regular readers of my blog might recall my post on Ruby mixins and C# 3.0 extension methods from last month. In that post I point out that extension methods resemble mixins, and since the spaceship operators true power comes from Ruby’s Comparable mixin this is a great opportunity to showcase the power of C# 3.0 extension methods.
We’ll use the IComparable<> and IComparable interfaces as a replacement for the spaceship, and since you cannot overload operators in an extension method, we’ll have to resort to named methods for the comparisons. A part from that we can get the whole shebang, including the Rubyesque between operator.

I’ve used the same Employee class as Abhinaba for my example, with the IComparable interfaces implemented.
class Employee : IComparable<Employee>, IComparable
{
    public Employee(string name, int jobGrade)
    {
        Name = name;
        JobGrade = jobGrade;
    }
    public string Name;
    public int JobGrade;

    public int CompareTo(Employee obj)
    {
        if (this.JobGrade
        else if(this.JobGrade==obj.JobGrade) return 0;
        else if (this.JobGrade>obj.JobGrade) return 1;
        return 0;
    }
    public int CompareTo(object obj)
    {
        Employee objAsEmployee=obj as Employee;
        if (objAsEmployee==null)
        {
            throw new ArgumentException("The parameter must be an Employee","obj");
        }
        return CompareTo(objAsEmployee);
    }
}

The client code is a no brainer. It just calls the extension methods on instances of the Employee class. The extension methods are mixed into the Employee implementation because I’ve added a using ComparableExtension directive to the application.
Employee employee1=new Employee("Arthur Dent",42);
Employee employee2=new Employee("Ford Prefect",10);
Employee employee3=new Employee("Trillian",15);
// Prints False
Console.WriteLine(employee1.LessThan(employee2));
// Prints True
Console.WriteLine(employee2.LessThanOrEqual(employee1));
// Prints True
Console.WriteLine(employee3.Between(employee1,employee3));

The interesting part is the implementation of the extension methods.
public static class ComparableExension
{
    public static bool GreaterThan(this object obj, object other)
    {
        return ((IComparable)obj).CompareTo(other)>0;
    }
    public static bool GreaterThanOrEqual(this object obj, object other)
    {
        return ((IComparable)obj).CompareTo(other)>=0;
    }
    public static bool EqualTo(this object obj, object other)
    {
        return ((IComparable)obj).CompareTo(other)==0;
    }
    public static bool LessThan(this object obj, object other)
    {
        return ((IComparable)obj).CompareTo(other)<0;
    }
    public static bool LessThanOrEqual(this object obj, object other)
    {
        return ((IComparable)obj).CompareTo(other)<=0;
    }
    public static bool Between(this object obj, object min, object max)
    {
        return (GreaterThanOrEqual(obj,min) && LessThanOrEqual(obj,max)) || (LessThanOrEqual(obj,min) && GreaterThanOrEqual(obj,max));
    }
}
As you can see from the code snippet above, this class is also fairly straight forward. The various comparison methods just use the IComparable interface on the objects to compare to determine whether they’re less than, equal to or greater than each other.

Domain Driven Design

A crucial threat against a project’s success is that it’s being put off course by developers having too much attention on technical issues, and hence forgetting to pay attention to the primary objective which is to solve business a business problem. A key job qualification for a developer is to know your programming language and the related technical frameworks, but this is far from enough. To ensure success, you must strive to understand the client’s business domain. You probably know a dozen technical design patterns, but have you ever though about how similar patterns can be applied within the business domain? Eric Evans, whom I’ve had the pleasure to meet on several occasions, has written an excellent book on this topic entitled Domain Driven Design. He also maintains a community website for people who are interested in not just developing code, but also delivering business value.

I’m sitting at my workstation,
Got a two inch stack of documentation. (Mmm.)
And each page looks the same to me
With Visitors and Factories,
And every data class I see
Reminds me that I long to be...

Chorus:
Domain Driven
We wish we was
Domain Driven
Domain, where the code's not breaking
Domain, where my head's not aching
Domain, where the system's speaking
Constantly to me

Our craft is programming, and we can never have the same knowledge about a business domain as a domain expert. Just as we do; domain experts have their own lingo, so to be able to discuss the business domain with the client you’ll need to get hip to the talk of the domain experts. As a consultant I’ve worked with vastly different businesses, ranging from transportation, to financial services and various governmental services to name a few. Usually, clients don’t expect you to be a domain expert, but if you don’t understand the business domain you run the risk of producing software that doesn’t adhere to a client’s understanding of the business rules.

Every class an endless stream,
Of muddled names and responsibilities. (Mmm.)
The shallow model frightens me
With subtle bugs that I can’t see.
This software runs the company
Won’t domain experts talk to me? 

(chorus)

In addition to being honest about only having layman’s knowledge about most business domains, I have two sharp tools to swiftly gain knowledge about arbitrary business domains; domain glossaries and Amazon. The Internet is flooded with great glossaries of various terms used within different industries. I’ve used glossaries of insurance, agricultural, shipping and many other terms. While glossaries are great to find the right name for an entity or operation on a class, you need to dig deeper to gain knowledge about the nuts and bolts of an industry. If you’re working on a project within the insurance sector, Emmet J. Vaughn’s Fundamentals of Risk and Insurance or even Jack Hungelmann’s Insurance for Dummies might be a good place to start.

Tonight I'm staying late again,
I'll play the game and pretend. (Mmm.)
Our big design comes back to me
In shades of mediocrity,
Like emptiness in harmony
This architecture's killing me. 

(chorus)

The lyrics are from Domain Driven – The song by Tracy Bialik and Russ Rufer, and it should be sung to the tune of Paul Simon and Art Garfunkel’s Homeward Bound. The song sings for it self, you should pay at least as much attention to your domain design as you do to your technical architecture. This doesn’t take the fun away from your projects, in fact it encourages you to develop an agile, lightweight technical architecture that doesn’t get in the way of the business challenges which is much more fun than writing a mega framework for a minor problem just to learn that it just doesn’t work.

Mock objects: Sealed doesn’t suck as much as it used to.

Back in 2003 Chris Sells wrote a blog post called ”Sealed Sucks” on the pros and cons of sealing a class. When I recently wrote some tests for an OR-mapping framework, I shared Chris’ feelings on the sealed keyword. The reason was simple, I had a class which mapped objects to stored procedures that exposed a single method to persist objects, and I had to ensure that the correct procedure was called, the correct parameters where passed to the procedure and so forth. The OR-mapper’s constructor expected a SqlConnection object as its parameter, so I figured that I’d just pass it a mocked SqlConnection.

NMock has been my tool of choice for mocking objects, but since SqlConnection is a sealed class you’ll get an exception if you try to mock it using NMock. Writing a mock SqlConnection by hand is neither an option, because you won’t be able to cast it to a SqlConnection.
Luckily, I came across a nifty mocking framework called TypeMock.NET which has the ability to mock any member of any concrete class, no matter whether the members are non-virtual or private, or the class is sealed. TypeMock.NET uses AOP-like techniques at the IL level to intercept usages of any type and member. It does this by using the .NET Framework’s profiler API to monitor execution. When the CLR loads a method, TypeMock.NET replaces the IL with calls to the mocked code.

Below is an example of how to assert that an a SqlParameter with the appropriate customer id is added to a SqlCommand’s Parameters collection when a Customer object is persisted.
[TestFixture]
public class DataServiceTest
{
            [SetUp]
            public void Setup()
            {
                        MockManager.Init();
            }
            [Test]
            public void TestDataService()
            {
                        Customer customer=new Customer();
                        customer.Id="42";
                        string connectionString="Mock Connection String";
                        Mock mockSqlConnection=MockManager.Mock(typeof(SqlConnection));
                        mockSqlConnection.ExpectConstructor().Args(connectionString);
                        Mock mockSqlCommand=MockManager.Mock(typeof(SqlCommand));
                        Mock mockSqlParameterCollection=MockManager.Mock(typeof(SqlParameterCollection));
                        mockSqlParameterCollection.ExpectAndReturn("Add",1).Args("CustomerID",customer.Id);
                        mockSqlCommand.ExpectCall("ExecuteNonQuery",1);
                        mockSqlConnection.ExpectAndReturn("CreateCommand",new SqlCommand());
                        DataService dataService=new DataService(new SqlConnection(connectionString));
                        dataService.SaveObject(customer);
            }
            [TearDown]
            public void TearDown()
            {
                        MockManager.Verify();          
            }

}

There are a couple of things to take note of in the above example. When I register mock objects for the SqlConnection, SqlCommand and SqlParameterCollection types, the actual mock objects aren’t created until I instantiate a new instance of either of the classes. This is the reason why I return an actual SqlCommand instead of a mock object in my mock implementation of SqlConnection.CreateCommand. Further, I do not need to manually create an instance of the SqlParameterCollection, because this class will automatically be mocked when the SqlCommand creates is Parameters collection.

Finally, I have to call the MockManger.Verify method to assert that all of my expectations have been fulfilled. This is akin to using Assert statements in a regular NUnit test.

Thanks to TypeMock.NET sealed doesn’t suck as much as it used to.