MIX07: Silverlight, IronRuby, and Dynamic Languages

Just came out of the MIX07 keynote. Very heavily focused on Silverlight and, specifically, its video encoding and delivery features.

Silverlight looks really, really cool. Turns out it’s a full CLR running within the Silverlight plug-in (at least that’s what I understood.) This means, of course, the CLR is running on a MAC. Another cool feature is that there’s an HTML DOM you can import inside of a Silverlight instance, allowing you to manipulate the hosting page with C#, etc. Like I said… cool.

The most interesting thing for me was the (underplayed) announcement of IronRuby and the extension of the .NET Framework CLR to support dynamic languages. I have to say the crowd reaction was tepid and underwhelming. Still, this is what I was hoping to hear. Dynamic language support (including IronRuby) will be hosted at CodePlex. There isn’t a link at this time.

Vegas or Bust

Packing up and heading out tomorrow for MIX07. A couple of developers from Xclaim (my company) are coming out with me. It’s gonna be awesome. Pending wireless access, I’m planning on doing some light live-blogging of the noteworthy reveals, my general impressions, etc.

If you’ll be there, shoot me an email (here, bottom of page) and let’s get a drink!

Styles of TDD: Left, Right, and Center

Martin Fowler wrote an article called “Mocks Aren’t Stubs” some time ago. In hit he explains the difference between Stubs objects and Mock objects characterizing them both as Test Doubles.

A Stub is designed to provide canned responses. They may also record the number of times a method was invoked or an event fired. Generally they appear in your test assembly as implementations of an interface or a subtype of another concrete type. Mocks, on the other hand, are objects that are setup with call expectations. There similar to a Stub in that canned responses may be offered up to fulfill a testing scenario. The real difference of a Mock is that the expectations get verified after running the actual test code. If all expected calls on the mock were made at least that portion of the test passes.

Hey then goes on to categorize two styles of testing: Classical TDD, and Mockist TDD. The term “Mockist” implies a value judgement, indeed Fowler sites that he prefers the classical style.

Gun Totin’ Conservatives

Classical TDD would have you using principally POCO objects and tests that allow you to reach across multiple classes for in any individual unit test. So, say you have a domain model with Order and OrderLine classes and you’re writing a test to verify that the Order calculates a total by the number of lines in it. Even though the unit under test is the Order class itself, a classical practioner wouldn’t mind bringing in the real OrderLine. If there was some behavior in the OrderLine that interfered with this test you may inherit OrderLine from a stub to fill in with some canned values. If your domain model is POCO enough, generally you could use the original OrderLine without a stub.

The classical style tends to encourage and promote state-based testing, e.g. Assert.IsTrue(myObject.Valid). Though, to be fair, arriving at that state is the product some black-box interaction between the unit under test’s dependencies or should be in a well factored codebase.

Volvo-Driving, Liberal Elites

Mockist TDD focuses on interactions between classes. In this style you have only one class under test, the other classes are built-up through a Mock Objects Framework such as Rhino, NMock2, or TypeMock. These mocked objects tend to be proxy implementations of the interfaces your class under test depend on. Each of these frameworks exposes, in their API, some kind of internal DSL (usually in the form of a fluent interface) by which expectations can be recorded. After you run the code under test there is some method you can call on a mock repository or factory (the object used to build up mocks) to verify that expectations were met.

While this style is heavily focused on interaction between classes there is usually some explicit state-based testing going on. I’ve used most of the popular mocking frameworks and still use NUnit’s asserts quite a bit. Often times the class I am testing will have some responsibility in producing some ultimate state: that it uses its dependencies to get there doesn’t absolve me from having to test relevant state on the class itself.

The Middle of the Road

I was asked by our Lead Developer at Xclaim, Rik, which I considered myself. Instinctively I responded Mockist. After mulling it over for a few days and re-reading the last half of the article I’d now say “a bit of both.” Sometimes I’m in a domain model that’s decoupled from lots of outside dependencies and I prefer the classical, state-based approach. I especially like it for DDD-style Entity and Value Objects patterns. When it gets into DDD-style services that may act on a variety of Entities and take dependency on infrastructure services (database, logging, etc.) I switch to mock mode without really thinking about it.

The main thing about the so-called Mockist style I like is it forces me to slow down and think through the design. Setting up all those expectations is much the same thing as writing down a sequence diagram on your whiteboard. In fact that’s a workflow I am using more often for complex problems.

Before I got hooked on TDD I took a play-dough approach to coding or what Steve McConnell calls “Code Like Hell.” Sure, that works, but you the product you end up isn’t usually that maintainable or well factored. You end up spending LOTS more time in debugging. When following employing TDD, while it seems slower,  you’re minimizing time spent on after-the-fact debugging and leaving a breadcrumb trail for both yourself and others.

The first hurdle I had to get through is the discipline to keep tests small and not to overextend my welcome while in the application code. The classic: “oh let me just do this (which doesn’t have a test) while I’m in here.” Bad Dave. Bad. The next hurdle for me was understanding how mock frameworks work and how to incorporate them into my state/assertion-based only test style. After all this I’d say I’m straddling both sides of the aisle, staying pragmatic, and using the right approach for the situation.

Refactoring My Template Method Post

Evan comments on my post I Heart Template Method:

one tiny suggestion for this object, instead of building the “one object to rule them all” base class, you could do the following:

create an interface IExecutable with one method, Execute()

then build a class for each technical concern (logging, transactions, security, eventing aka observation, caching)…

each of the classes can implement IExecutable and take another IExecutable in their constructor… it’s a simple way to layer each on top while keeping true to the single responsibility and open/closed principles..each class performs its responsibility and then delegates to the next object (passed into the constructor) until the final object gets executed (the real Task object).. it gives you the freedom to change one technical concern without affecting the others..or providing multiple implementations of a particular concern (ie..two caching modes). you can also apply some concerns to some tasks while leaving others off (or rearranging the order of execution).. you can think of them as mini-layers on top of your task object (which also implements IExecutable)

you can either wire the whole thing up with a DI container or create a factory to add the objects onto the task objects (depending on the app)

Great comment. I’m not sure this is a one object to rule them all situation, but maybe so I’ll bite and get to refactorin’. Recall my original, now bug free, example:

public abstract class TaskBase
{
   public void Execute()
   {
      using (TransactionScope scope = new TransactionScope())
      {
         OnBeforeExecute();

         ExecuteTask();

         OnAfterExecute();
         LogExecution();
         scope.Complete();
      }
   }

   protected void OnBeforeExecute()
   {
      if (BeforeExecute != null) BeforeExecute(this, EventArgs.Empty);
   }

   protected void OnAfterExecute()
   {
      if (AfterExecute != null) AfterExecute(this, EventArgs.Empty);
   }

   public event EventHandler BeforeExecute;

   public event EventHandler AfterExecute;

   private void LogExecution()
   {
      // write event details to 
      // some durable resource
   }

   protected abstract void ExecuteTask();
} 

Template Method by Way of Generics, Constructor Injection

The first piece of the comment I’ll tackle is the idea that I have this big, abstract, “magic”, do-it-all class and that my simple framework based on Template Method is violating Single Responsibility Principle (SRP) and Open-Closed Principal (OCP). I’ll buy that. I can decouple the base class from our individual task implementations by keeping the Template Method but moving away from a Layer SuperType. I’ll define an ITask class and a TaskExecutor<TTask> class. We can constrain TTask to require a class implementing ITask. 

Furthermore, I’ll make TaskExecutor<TTask> use constructor injection so my transaction service can be swapped out in regular code, an IoC container, or with a mocking framework. This step gets me back in the good graces of SRP. It’s worth mentioning that I’m using a tiny Role Interface for ITask. My task classes can now be straight-up POCOs with all the associated benefits. I’m still keeping the spirit of Template Method here, just freeing up my one base class for whatever class ultimately inherits ITask. It’s interesting to note that in the C++ world the (more-or-less) equivalent of C# Generics are called Templates.

The code after these changes:

public interface ITask
{
   void Execute();

   bool NeedsTransaction { get; }
}
public class TaskExecutor<TTask>
   where TTask : ITask
{
   private readonly TTask _task;
   private readonly ITransactionService _transactionService;

   public TaskExecutor(TTask task)
   {
      _task = task;
      if (_task.NeedsTransaction)
         _transactionService = new ProductionTransactionService();
   }

   public TaskExecutor(TTask task, ITransactionService service)
   {
      _task = task;
      _transactionService = service;
   }
   public void Execute()
   {
      if (_task.NeedsTransaction)
         ExecuteTransactionalTask(_task);
      else
         _task.Execute();
   }

   private void ExecuteTransactionalTask(TTask task)
   {
      using (ITransactionScope scope = _transactionService.GetScope())
      {
         task.Execute();
         scope.Complete();
      }
   }
}

Did you notice I have two constructors? The constructor with two arguments is used for tests. I’d also use it if it every became desirable to introduce an Inversion-of-Control container in my application. I’ve created an ITransactionService interface that’s easily faked by hand or mocked using your favorite mock object framework. Of course my original post was way too ambiguous. It assumes a framework where all tasks are transactional. Shame on me for not being explicit with this, I can see reason to cry foul. Let’s right previous wrongs and make things explicit.

Our ITask implementations must tell our framework if it needs a transaction by giving it a NeedsTransaction property. We could choose to take control of transactions inside each individual ITask implementation, but that kind of muddies the goal of making ITasks dead easy and focused on the, well, task at hand. Furthermore, it violates another principal of good design: Don’t Repeat Yourself, The DRY Principal. Balancing all of these concerns I’m making the decision to leave transaction coordination inside the TaskExecutor. This still leaves us with a good SRP quotient; TaskExecutor now depends on a seperate service for transactions. 

OK, enough on that.

Extending the Behavior of Task Execution

Here we have a couple of options. I’ve mentioned Chain of Responsibility, so let’s go down that route.I’ll define a handler abstract base class for code in our pre- and post-execution pipeline. With my alternative design I’ll swap out Observer (the BeforeExecute and AfterExecute events) for two properties and some additional logic in TaskExecutor.Execute(). Now, an important question I have to ask myself here: does the order of pre- and post-execution handlers matter? For the sake of argument, let’s say “sure”, Chain of Responsibility is a good choice, and move on with life.

Here’s what the refactored TaskExecutor class looks like with the changes in bold:

public class TaskExecutor<TTask>
   where TTask : ITask
{
   private readonly TTask _task;
   private readonly ITransactionService _transactionService;
   private ExecutionChainHandler<TTask> _beforeExecutionChain;
   private ExecutionChainHandler<TTask> _afterExecutionChain;

   [CoverageExclude]
   public TaskExecutor(TTask task)
   {
      _task = task;
      if (_task.NeedsTransaction)
         _transactionService = new ProductionTransactionService();
   }

   public TaskExecutor(TTask task, ITransactionService service)
   {
      _task = task;
      _transactionService = service;
   }

   public ExecutionChainHandler<TTask> BeforeExecutionChain
   {
      set { this._beforeExecutionChain = value; }
   }

   public ExecutionChainHandler<TTask> AfterExecutionChain
   {
      set { this._afterExecutionChain = value; }
   }

   public void Execute()
   {

      if (this._beforeExecutionChain != null)
         this._beforeExecutionChain.HandleWithinChain(_task);

      if (_task.NeedsTransaction)
         ExecuteTransactionalTask(_task);
      else
         _task.Execute();

      if (this._afterExecutionChain != null)
         this._afterExecutionChain.HandleWithinChain(_task);

   }

   private void ExecuteTransactionalTask(TTask task)
   {
      using (ITransactionScope scope = _transactionService.GetScope())
      {
         task.Execute();
         scope.Complete();
      }
   }
}

I’ve also defined another class ExecutionChainHandler and its implementation looks like this:

public abstract class ExecutionChainHandler<TTask> where TTask : ITask
{
   private ExecutionChainHandler<TTask> _nextHandler;

   public ExecutionChainHandler<TTask> NextHandler
   {
      set { _nextHandler = value; }
   }

   public void HandleWithinChain(TTask task)
   {
      Handle(task);
      if (_nextHandler != null)
         _nextHandler.HandleWithinChain(task);
   }

   public abstract void Handle(TTask task);
}

By defining both pre- and post-execution Chains of Responsibility I stay on the good side of the Open-Closed Principle. It’s certainly easy to modify Task execution and inject additional validation or processing logic before and after.

One thing you’ll notice in this framework is that ExecutionChainHandler<TTask> takes a specific task. This approach wouldn’t be ideally suited for creating generic services like caching… at first glance. We can, however, treat each implementation of ExecuteChainHandler<TTask> as a Adapter into a common, generic service. Say we have a task implementation called GetCustomerData. Maybe in the pre-execution chain we want to check to see if some necessary data is in a cache. In this case, with what I’ve got here, I’d probably need to refactor a “shortcut” or “interrupt” mechanism to enable ExecutionChainHandler’s to shortcut the rest of the chain and task execution as a whole (perhaps), but I’d certainly employ an Adapter to a more cross-cutting, but single responsibility, service. One can imagine a generic ICacheService.

What’s the Point?

Is this code complete? Hell no. Does it represent anything real world? Well I suppose it could, but that’s not my intention.

On the surface I’m illustrating a better, more testable, generics-based Template Method. I show how you can select and apply lots of patterns in the process of defining a little framework. The keyword there is selection. When you first get into this stuff there’s an awful tendency to indulge in using every pattern you can think of: solutions in search of a problem. Patterns can be your friends and work well together when you start out with a simple approach and match them to the problem your are facing. The key is to break down the problem into small chunks then, when it makes sense, apply the pattern that matches a) the context of your problem and b) whose forces you can live with.

Beyond solving business problems, you need to consider the problem of the maintainability of your code. Tried-and-true principles such as OCP and SRP belong in every developer’s default checklist and go a long way in deciding which patterns to employ and where.

Software 2017

Here’s a video from InfoQ of a JAOO 2007 panel with Martin Fowler, Frank Buschmann, Steve Cook, Jimmy Nilsson, and Dave Thomas discussing the future of software development. Sure it’s the tired and typical panel format but it does hit on more than a few interesting points.

Maybe you could watch it over lunch tomorrow with a tasty sandwich or something?

Anyway, the central theme is the question: who will develop software in 10 years? 

SPOILER ALERT!

In case you don’t have time to watch the video I’ll provide the answer: people will develop software in 10 years.

ALT.NET

Scott Bellware has post entitled “On Being the NHibernate Mafia.” The term “NHibernate Mafia” is amusing to say the least.

In the post Scott rejects the term and gets at the ethos he, I, and lots of others are trying to evangelize and bring to the .NET community: It’s not the tools, it’s the solution. For me it’s often the maintainability of the solution. How easy can I evolve/change the solution? I’ll tell you what, I’m sick and tired of dealing with legacy code.

If there has to be a label, I’ll propose a new one: ALT.NET

What does it mean to be to be ALT.NET? In short it signifies:

  1. You’re the type of developer who uses what works while keeping an eye out for a better way.
  2. You reach outside the mainstream to adopt the best of any community: Open Source, Agile, Java, Ruby, etc.
  3. You’re not content with the status quo. Things can always be better expressed, more elegant and simple, more mutable, higher quality, etc.
  4. You know tools are great, but they only take you so far. It’s the principles and knowledge that really matter. The best tools are those that embed the knowledge and encourage the principles (e.g. Resharper.)

When tools, practices, or methods become mainstream it’s time to get contrarian; time to look for new ways of doing things; time to shake it up. The minute Entity Framework surpasses NHibernate, I mean the very instant it empowers me to better express my intent, so long NHibernate. It’s been real, it’s been nice, but I’m on to the better thing. Of course it’s not as black-and-white as all that. It’s up to us to stay aware, educated, and to give our input. It’s not a game of wait-evaluate-wait-evaluate, it’s a matter of contribution.

Sidebar: You know I wouldn’t call the meeting between the Agile folk and Microsoft’s ADO.NET team the “Entity Framework Smackdown.” It was a “Mind Meld” and a healthy one at that. There was a lot of passion going on, to be sure, but folks were listening to each other all around.

Ralph Waldo Emerson wrote “there are always two parties; the establishment and the movement.” If you’re ALT.NET, you’re in the movement. You’re shaking out the innovation. When the movement fails, stalls, or needs improving you’re there starting/finding/supporting that next leap forward.

Get With Twitter

After try to grok the utility value of tumblelogs (and failing) I got on twitter. Why not add me as a friend, friends?

http://twitter.com/laribee

R.I.P. PatternShare.org?

Looks like patternshare.org is dead. Could this be the case or is this report of its demise greatly exaggerated? I’ll admit the resource never was what it could be, but it was useful as a jumping off point, for the basics.