If I was going to build a little plastic house out of Legos, I would probably start by finding a nice, flat baseplate piece. A green one, in a solid school district. My next step would not be, however, to start building the walls out of horse blocks.

Having the right Legos on your table (as the belabored metaphor goes) can go a long way when you’re trying to build software. Even with modern tools and frameworks, there is an entropy we battle in this process. The right pieces don’t just happen, especially if you’re sauntering through the designer and stuffing VB into whatever event handler Studio is holding open for you at the moment. I’m just guessing about the VB.

So here’s a pattern that I picked up that will make your code at once more readable, reusable, and maintainable.

Ladies.

LINQ to Awkward

Let’s say we have some business code that looks like this. Because you maybe probably do.

using (var db = new AdventureWorksEntities()) {
 
    // get orders from the last week
    // that were made online
    // and that have a tax amount greater than half of the subtotal
    var orders = from p in db.SalesOrderHeaders
                 where p.OrderDate >= DateTime.Today.AddDays(-7)
                    && p.OrderDate <= DateTime.Today
                    && p.OnlineOrderFlag
                    && p.TaxAmt > (p.SubTotal / 2)
                 select p;
 
    foreach (var order in orders) {
 
        // if they're related to me,
        if (order.Contact.LastName == "Fazzaro") {
 
            // give them a fifty percent discount
            order.SubTotal *= (decimal)0.5;
        }
    }
 
    db.SaveChanges();
}

Not too shabby. Most developers would have no issue taking this snippet under their wing and showing it a nice afternoon in a text editor.

But look closer. Those comments unveil four or five distinct aspects of SalesOrderHeader data that are being tested before any action is taken, all crammed together into one awkwardly equine block of functionality. It’s terribly specific in nature, and probably not really reusable at all.

Don’t see it yet? Watch this.

You Have FAIL

Ding. There’s a new message in your Inbox. It’s the oh-by-the-way requirement that we also need to do something just like this, but with all orders (not just online orders) and also only orders from two weeks ago oh and also not made on a Thursday because Thursdays are when Dianne has her meeting with the supply chain something something can you speak to when we can expect to maybe talk about having that this afternoon?

So, of course, it’s copy-and-paste inheritance all the way to the check-in button, and now you just want to go wash, and maybe look at some Ruby code. Which, I hear, is lovely this time of year. And so are the mangoes.

Meanwhile, your not-really-reusable-at-all horse block of code is now two nearly-identical not-really-reusable-at-all horse blocks of code:

public void DoitOneWayForOnlineOrdersFromLastWeek() {
    using (var db = new AdventureWorksEntities()) {
        // get orders from the last week
        // that were made online
        // and that have a tax amount greater than half of the subtotal
        var orders = from p in db.SalesOrderHeaders
                        where p.OrderDate >= DateTime.Today.AddDays(-7)
                        && p.OrderDate <= DateTime.Today
                        && p.OnlineOrderFlag
                        && p.TaxAmt > (p.SubTotal / 2)
                        select p;
        foreach (var order in orders) {
            // if they're related to me,
            if (order.Contact.LastName == "Fazzaro") {
                // give them a fifty percent discount
                order.SubTotal *= (decimal)0.5;
            }
        }
 
        db.SaveChanges();
    }
}
 
public void DoitAnotherWayForAnyOrderFromTheWeekBeforeLastButNotOnThursdaysBecauseDianneHasThatThingYouKnow() {
    using (var db = new AdventureWorksEntities()) {
        // get orders from two weeks ago
        // not made on a Thursday 
        // and that have a tax amount greater than half of the subtotal
        var orders = from p in db.SalesOrderHeaders
                        where p.OrderDate >= DateTime.Today.AddDays(-14)
                        && p.OrderDate <= DateTime.Today.AddDays(-7)
                        && p.OrderDate.DayOfWeek != DayOfWeek.Thursday
                        && p.TaxAmt > (p.SubTotal / 2)
                        select p;
 
        foreach (var order in orders) {
            // if they're related to me,
            if (order.Contact.LastName == "Fazzaro") {
                // give them a fifty percent discount
                order.SubTotal *= (decimal)0.5;
            }
        }
 
        db.SaveChanges();
    }
}

You can see how this gets out of hand quickly. We can do better.

.OkayLetsDoBetterThenAndGetOnWithItBecause(this Article isAlreadyHalfwayOver)

How can we do better? By annotating our data types to expose discrete parts of queries as methods. Duh.

In reviewing our smelly old code, we find that the following five conditions of Orders are tested:

  • Whether the order date is within a given range
  • Whether the order was made online
  • Whether the order has a tax amount greater than half of the order’s subtotal
  • Whether the order was made on a certain day of the week
  • Whether the order was placed by somebody perhaps related to your humble narrator

Wouldn’t it be loverly if we could just ask a steaming pile of SalesOrderHeaders for these things, one at a time, in plain English? Picture it. Seriously, see it first—great APIs start by envisioning the consuming code up front:

var myOrders = db.SalesOrderHeaders
                .From(DateTime.Today.AddDays(-7))
                .To(DateTime.Today)
                .FromOnline()
                .ThatAreHighlyTaxed()
                .ThatWereMadeOnA(DayOfWeek.Thursday)
                .OrderedByARelative();

What’s killer about what we’re about to pull off here is that we can make this happen without ever sullying our data access code. We can keep the logic in a totally separate layer. This is made possible by the modern .NET miracle of Extension Methods, a feature introduced in .NET 3.0, largely to make LINQ possible at all. And in the same way NASA indirectly gave us a really pretty nice pen because Neil and Buzz and pals needed to scratch chickens whilst being floaty and disoriented, the benefits of the necessity extend beyond the mother of their invention. See what I did there? Extend. Moving on.

Where were we? Right. Adding a file in our logic layer that defines a set of extension methods to (in this case) IQueryable<SalesOrderHeader>:

public static class SalesOrderHeaderQueryExtensionsYo
{
    public static IQueryable<SalesOrderHeader> From(this IQueryable<SalesOrderHeader> orders, DateTime from)
    {
        return orders.Where(p => p.OrderDate >= from);
    }

    public static IQueryable<SalesOrderHeader> To(this IQueryable<SalesOrderHeader> orders, DateTime to)
    {
        return orders.Where(p => p.OrderDate <= to);
    }

    public static IQueryable<SalesOrderHeader> FromOnline(this IQueryable<SalesOrderHeader> orders)
    {
        return orders.Where(p => p.OnlineOrderFlag);
    }

    public static IQueryable<SalesOrderHeader> ThatAreHighlyTaxed(this IQueryable<SalesOrderHeader> orders)
    {
        return orders.Where(p => p.TaxAmt > (p.SubTotal / 2));
    }

    public static IQueryable<SalesOrderHeader> ThatWerePlacedOnA(this IQueryable<SalesOrderHeader> orders, DayOfWeek dow)
    {
        return orders.Where(p => p.OrderDate.DayOfWeek == dow);
    }

    public static IQueryable<SalesOrderHeader> OrderedByARelative(this IQueryable<SalesOrderHeader> orders)
    {
        return orders.Where(p => p.Contact.LastName == "Fazzaro");
    }
}

Each of these extension methods alters the given IQueryable<SalesOrderHeader> by a single condition and returns it. This lets us stack them together helter-skelter pell-mell all day long. By virtue of the IQueryable bit, the full query only actually executes when you access the results (say, in a foreach loop) so there is no performance drag incurred by building our LINQ piecemeal. It’s as if we were still writing one solid query, like before—only now we’re writing it by snapping bits together in whatever combination tickles our toes.

Sort of like building a small plastic house with the right Legos.

So, using this new fluent API, a full re-creation of the original consuming code from above would look something like

using (var db = new AdventureWorksEntities())   // for online orders, etc.
{
    db.SalesOrderHeaders
        .From(DateTime.Today.AddDays(-7))
        .To(DateTime.Today)
        .FromOnline()
        .ThatAreHighlyTaxed()
        .OrderedByARelative()
        .ToList()
        .ForEach(p => {
            p.SubTotal *= (decimal)0.5;
        });
    db.SaveChanges();
}

// elsewhere...

using (var db = new AdventureWorksEntities())   // not thursdays, etc.
{
    db.SalesOrderHeaders
        .From(DateTime.Today.AddDays(-14))
        .To(DateTime.Today.AddDays(-7))
        .Except(db.SalesOrderHeaders.ThatWerePlacedOnA(DayOfWeek.Thursday))
        .ThatAreHighlyTaxed()
        .OrderedByARelative()
        .ToList()
        .ForEach(p => {
            p.SubTotal *= (decimal)0.5;
        });

    db.SaveChanges();
}

And if the definition of that somewhat-contrived ‘highly-taxed’ condition needed to change, we wouldn’t spend an anxiety-stricken morning hoping to find it in everywhere the code, with all its subtle variations, to get it updated. We could just waltz on into that beautiful DRY extension method, and tweak it once.

public static IQueryable<SalesOrderHeader> ThatAreHighlyTaxed(this IQueryable<SalesOrderHeader> orders)
{
    // Fred in finance says this should be 1/3, not 1/2. 
    // Also: totally waltzing right now.
    return orders.Where(p => p.TaxAmt > (p.SubTotal / 3));    
}

And if eventually the logic is altered so much that the method’s name no longer makes sense? We’ll just change the name, and take Visual Studio up on it when we are offered the auto-renaming Smart Tag. Boom.

Now imagine the rest of our code behaving itself like this and being all composable and readable. Say, while loading up a grid control with Monday orders within a date range?

var db = new AdventureWorksEntities();
mondayOrdersGridView.DataSource = db.SalesOrderHeaders.From(fromDate).To(toDate).ThatWerePlacedOnA(DayOfWeek.Monday);
mondayOrdersGridView.DataBind();

Go Forth And Extend

More so than its debatably breathtaking user interface, or its over-clever ORM plumbing, your app’s domain logic is what really gives it any value at all. Building and maintaining that logic code should be more of a flowy, compositional experience, and not so much of a making minimum payments on your technical debt sort of thing that you do to kill time between weekends.

It’s also worth noting that a writability and readability gain with a zero performance hit is a rare thing in our line of work, so you should probably quit making those two horse blocks kiss and get on that.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s