Entries
RSS 2.0

Comments
RSS 2.0

So what, you’re my Master now?

My wife Nicole is graduating today with a Master’s degree in Industrial / Organizational Psychology from the University of Akron. It’s a great accomplishment, but she’s not that excited… she’s on the MA/PhD track, meaning that although she’s graduating, she’s immediately going back for another 3 years to complete her PhD. In spite of it just being “another milestone” in her educational career, it’s a very significant one, and I’m very proud of her.

Error Messages and the "Try Again Later" Syndrome

When your application communicates with the user, it should do so in a way that is helpful. One of the most important times that software communicates with the user is when an error occurs. This can be a very delicate situation, because the user is unlikely to be pleased that their request was denied. There is an art to error messages that is sadly lacking in most software.

Error messages should never:

  1. Give too little information.
  2. Give too much information, unnecessarily confusing the user.
  3. Provide no solution to the problem.
  4. Make the user so angry that he/she smashes the monitor.

For example, take this, one of my favorite error message from Windows XP:

try-again-later

I see this message about 50% of the time when I try to “safely remove” my portable WD Passport hard drive. Every time I see this message, it makes me want to drive to Redmond and start dealing out ass-whippings give everyone a stern talking-to. Simply put, this message exemplifies everything that’s wrong with error messages. If it would tell me what application was locking the file on the disk, I would shut it down. I would even be happy to kill it with the task manager. Sadly, I get no hints. I’m sure this error message was easy to write, but it’s no more useful than the “lazy programmers” haiku error message by Charlie Gibbs:

Errors have occurred.
We won’t tell you where or why.
Lazy programmers.

Error messages are important for normal applications, but nowhere are they more important than in software libraries. With Ninject, I’ve gone through great pains to make the exception messages as useful as possible. Here’s an example error message, in this case if you try to activate a service that has a circular reference with another service. (Note that the web layout might cause odd word wrapping. Trust me that it’s formatted a little more cleanly. :)

Ninject.Core.ActivationException: Error activating CircularMockA:
Circular dependencies detected between constructors. Consider using property injection and implementing IInitializable instead.
Using default self-binding of CircularMockA (via StandardProvider)
  declared by SampleModule.Load() at SampleModule.cs:85
Activation path:
  3) passive injection of service CircularMockA into parameter mockA on constructor of type CircularMockB
     using default self-binding of CircularMockA (via StandardProvider)
     declared by SampleModule.Load() at SampleModule.cs:85
  2) passive injection of service CircularMockB into parameter mockB on constructor of type CircularMockB
     using default self-binding of CircularMockB (via StandardProvider)
     declared by SampleModule.Load() at SampleModule.cs:86
  1) active request for CircularMockA
     from Program.Main() at Program.cs:91
     using default self-binding of CircularMockA (via StandardProvider)
     declared by SampleModule.Load() at SampleModule.cs:85

This is a good error message. It clearly describes what happened, and gives a possible solution. It directs the user back to the exact line number where the error occurred (which is sometimes lost when exceptions get wrapped). It then goes so far as to show every step in the activation process, starting with the first time the user asked Ninject for something — the active request, shown last. That way, if the user doesn’t quite understand how activation works in Ninject, they should still be able to understand what the framework is doing. This is in addition to the stack trace that is available with all exceptions in .NET.

If I wanted to pattern my exception message around the one from the Safely Remove Hardware applet, it would look more like this:

System.Exception: Couldn't complete request. Try again later.

There are some libraries out there that have fantastic error messages. The Castle Project (particularly MonoRail) and Guice come to mind. However, some libraries that are otherwise great (NHibernate, I’m looking at you) have some terrible error messages.

I’m guilty of this too. One of the first applications I wrote when I started programming professionally was a PDF generator, written in C++. It was designed as an executable, and controlled by command-line parameters. This utility was embedded in other systems, primarily in a Linux environment, so we decided to use shell-return codes to indicate if there was a problem with the generation of the PDF. Sadly, we ran out of time before we implemented the error code system. To this day, the application returns one of three codes:

  • -1: There was a problem with configuration.
  • 0: The PDF was successfully generated.
  • 1: There was some sort of error generating the PDF.

Once the utility was configured, its configuration wouldn’t generally change, so 99% of errors just return 1. We were creative enough, though, to include a log file, which could be configured to dump the entire contents of the PDF document in a debug-type display. It was even output in HTML, with some JavaScript to expand and collapse the giant tree in which it was displayed. Unfortunately, there wasn’t any real level-filtering of the log… it was either on or off. So, if you tried to generate a 200 page PDF, your log file would be somewhere around 300MB of HTML. Try loading that in Internet Explorer and clicking the “expand all” button… :)

My point of all this rambling is this: errors happen, and reporting them correctly is a vital part of any piece of software. If you’re going to spend the time to write a killer application, or a killer library, make sure you spend time to deliver proper error messages to your users. As a good exercise, show your error message to a user who understands how your application works and ask: can you explain what the problem is by reading this? If the answer is no, it’s time to go back to the drawing board. It’s tempting to just say “shit’s broke, try again later”, but you’ll pay for it eventually.

Functional Magic

In the shower this morning, as the haze of sleep was clearing, I was thinking about delegates in C#. (Yes, I’m a complete and total geek. As if there was any debate on that issue. :) An interesting thought occurred to me, though, so I naturally had to throw together a proof of concept. It’s another one of those ideas whose usefulness is debatable for most cases, but is interesting nonetheless.

A functor, which is a term from functional programming, is an function represented as an object. In C#, functors are implemented as delegates. C# 2.0 introduced some language features like implicit delegate creation and invocation, which give the appearance of first-class functions. This significantly narrows the gap between actual method declarations and delegates.

A class is essentially a collection of methods along with some data that defines its state. Consider this class definition:

   1: public class Formatter
   2: {
   3:   public string Format(string message)
   4:   {
   5:     return message.ToLower();
   6:   }
   7: }

Very straightforward. To use this Formatter class, you could do something like this:

   1: public static class Program
   2: {
   3:   public static void Main()
   4:   {
   5:     Formatter fmt = new Formatter();
   6:  
   7:     // Outputs “my message!”
   8:     Console.WriteLine(fmt.Format(“My Message!”));
   9:   }
  10: }

Nothing groundbreaking there either. But what if, instead of actually defining your method directly, you did this instead?

   1: public class Formatter
   2: {
   3:   public Functions.Format Format = delegate(string message)
   4:   {
   5:     return message.ToLower();
   6:   }
   7:  
   8:   public class Functions
   9:   {
  10:     public delegate string Format(string message);
  11:   }
  12: }

Take a close look at that snippet. Rather than declaring a Format method on the Formatter type, we’ve given it a public Format field. The Format field is of type Formatter.Functions.Format, which is a delegate defined in an inner class called Functions. (The inner type just keeps the outer Formatter type clean of any delegate definitions.) Then, using anonymous method syntax, we’ve assigned the Format field a value, which is the same as our previous implementation of the Format method.

What we’ve essentially done is separated the signature of the method from its implementation. You can still use the Formatter just like before:

   1: public static class Program
   2: {
   3:   public static void Main()
   4:   {
   5:     Formatter fmt = new Formatter();
   6:  
   7:     // This triggers the Format delegate, resulting in the same
   8:     // output of “my message!”
   9:     Console.WriteLine(fmt.Format(“My Message!”));
  10:   }
  11: }

But, since the implementation is separate from the declaration, we can do fun stuff like:

   1: public class Program
   2: {
   3:   public static void Main()
   4:   {
   5:     Formatter fmt = new Formatter();
   6:  
   7:     // Change the implementation of Format.
   8:     fmt.Format = delegate(string s) { return s.ToUpper(); };
   9:  
  10:     // This outputs “MY MESSAGE!”
  11:     Console.WriteLine(fmt.Format(“My Message!”));
  12:   }
  13: }

You could even get more creative:

   1: public class Program
   2: {
   3:   public static void Main()
   4:   {
   5:     Formatter fmt = new Formatter();
   6:  
   7:     // Save a copy of the original implementation (ToLower)
   8:     Formatter.Functions.Format func = fmt.Format;
   9:  
  10:     // Wrap the function with another implementation.
  11:     fmt.Format = delegate(string s) { return “The message is [" + func(s) + "]“; };
  12:  
  13:     // This will output “The message is [my message!]“
  14:     Console.WriteLine(fmt.Format(“My Message!”));
  15:   }
  16: }

This technique is used pretty commonly in dynamic languages like Ruby, but it can still be applied to more static languages like C#. Arguably, it would be nice if there was support for this in the language (say through the virtual keyword, or a new one like externalizable), but I have a feeling it would be misused pretty quickly. :)

Embracing Change

(Or, How I Learned to Stop Worrying and Love Dependency Injection)

The dependency injection debate has continued to rage. Jacob posted a reply to Ayende’s two posts, which Ayende then responded to. Donald Belcham (the Igloo Coder) also got in the act. The debate has basically been geared around a few questions:

  1. Is there merit to dependency injection outside of unit testing and mocking?
  2. Is dependency injection alone enough to allow loose coupling?
  3. Is it dangerous to rely on a container to do “voodoo” to wire up objects?
  4. Doesn’t relying on interfaces violate YAGNI?

First off, I believe (as I’ve stated before) that there is a lot of benefit in dependency injection above and beyond unit testing. My development is not quite test-driven (yet), but I consistently rely on dependency injection to guide me in designing my software’s architecture. In my experience, the best feature of DI is that it makes it natural to separate concerns. Like most developers, I’m lazy, so if something is easy, it’s more likely to become second nature. These days, it’s very unlikely for me to accidentally violate SRP.

However, I think I haven’t been clear about one aspect of my stance: I also believe that dependency injection by hand is probably worse than using factories. As Jacob pointed out, by exposing the dependencies of a type, you can actually increase your coupling, because you’re requiring that any code that consumes your type also has knowledge of the type’s dependencies. Likewise, types that consume that type must know about the original types dependencies, and so on. In real-world scenarios, dependency injection by hand simply does not scale.

Enter a dependency injection framework. In the past, I’ve referred to embracing a dependency injector as going Hollywood (from the Hollywood Principle: “don’t call us, we’ll call you”). If you go Hollywood, you submit yourself to the glitz and glamour of your injector, with its fancy XML mapping files or [Inject] attributes. Relying on a bunch of voodoo like reflection to wire up your objects might seem daunting at first, but it has a very important purpose: it effectively means you never have to think about how your objects need to communicate. You just need to know which objects need to talk to which. Tell the injector, and it will figure out the rest.

I can understand the reluctance to give up control over such a fundamental aspect of your software, but you do it already. There’s this big elephant of a framework called the CLR hiding behind our software, and no one is complaining (too loudly) about the things it does to and for us. Adding a dependency injector into the mix is just another step, and if it lets me be lazy about busywork like wiring up objects, then sign me up! I think there’s a preconceived notion about people who consider software from an architectural perspective, that somehow we are more interested in the elegance of the system than in what it does for its users. I can’t speak for everyone, but for me, I just recognize that a good architecture means I can spend more time adding features, and less time doing mundane tasks.

I’d say that there’s different levels of commitment to dependency injection, too. You can use DI with or without programming against interfaces. I tend toward the latter because, while it’s more work, it’s another tool that helps me to design my software. If I’m designing a service-oriented architecture, defining interfaces for each of my services makes it easier to keep the interaction points simple. In spite of my interest in DI, I’m still very much a proponent of information hiding, and it’s very difficult to “over-expose” a type when you have to add them to an interface definition. Sure, I might never make another concrete implementation of an interface. But, if it’s there, I can take advantage of it if I need it. Not to mention that with a dependency injector, it’s perfectly natural to program against interfaces anyway — after all, there’s no constructors to call!

I made a comment, which has been repeated by Ayende, that dependency injection (particularly when used with interface-based development) makes your code easier to change. The tools that we have today for refactoring are great, but they aren’t magical. If you couple your types together too tightly, or jam all sorts of concerns into the same type, you will have a hell of a time separating them when it becomes necessary. Trust me. I’ve been there.

Great effort has been applied in .NET to supporting configuration. To me, programming against interfaces and using a dependency injector to wire everything up is a lot like putting connection strings in a configuration file. Sure, you can hardcode constants. They’re not going to change today, or maybe even for the foreseeable future. But they will. Given enough time, all requirements change. I’d rather plan for the inevitable.

I think what everyone is missing is that this is not a zero-sum game. No one is saying that if you don’t use dependency injection, your software will turn into a big ball of mud, your friends will abandon you, and your dog will bite you when you try to pet it. Likewise, no one is saying that if you embrace dependency injection, your code will turn into a symphony of light, become sentient, and begin to write itself while you nap at your desk. It’s just a principle to follow, like information hiding or single-responsibility. It can be misused, but if used correctly, it can and will change the way you think about software — and I think for the better.

Dependency Injection: The Cavalry Has Arrived

If you’ve been following the conversation between Jacob Proffitt and myself about dependency injection, Ayende Rahien has added his thoughts to the topic as well in two posts on his own blog:

Dependency Injection: More than a testing seam
Dependency Injection: IAmDonQuixote?

This started from Jacob’s first post on his blog, which I commented on, and it spun off into an article on my own blog (and continued in the comments). It’s turned into a very interesting conversation on the merits of dependency injection versus alternatives such as the provider model used in ADO.NET.

Update: Aaron from Eleutian has also joined the conversation.
Update 2: Eli Lopian (of TypeMock fame) has also presented his stance.

Defending Dependency Injection

A few days ago, I read an article on Jacob Proffitt’s blog (Scruffy-Looking Cat Herder) about dependency injection. In the article, Jacob questions whether there are real benefits of dependency injection (DI) above and beyond additional testability. I challenged his stance in a comment, and he replied. I highly suggest that you read the article and the comments, because he’s posing a very good question.

First, a couple of definitions, in case you’re not familiar:

  1. Cohesion is the measure of semantic similarity between the code in a given logical segment. Highly-cohesive code is better code. (See also the Single Responsibility Principle, the optimal level of cohesion in object-oriented software.)
  2. Coupling is the measure of how much a given logical segment of code relies on other segments. Loosely-coupled code is better code.

Essentially, Jacob asserts that dependency injection raises the coupling in your code by pushing the need to understand dependencies of a given type outside of the type itself. As he says:

How can you say that dependency injection…creates loosely coupled units that can be reused easily when the whole point of DI is to require the caller to provide the callee’s needs? That’s an increase in coupling by any reasonable assessment.

This was precisely my first thought when I was originally exposed to the idea of dependency injection, because it goes directly against what we’ve been taught about object-oriented programming. The principle of encapsulation, one of the pillars of object-oriented design, states that if information doesn’t need to be exposed publicly from a class, it should be hidden from any code that consumes it. Encapsulation of data and logic is great, because it reduces the surface area of your classes, making it easier to understand how they work, and more difficult to break them.

Here’s the secret that makes dependency injection worthwhile: when it comes to dependencies, encapsulation is bad.

Consider the following code:

   1: public abstract class Engine
   2: { … }
   3:  
   4: public class V6Engine : Engine
   5: { … }
   6:  
   7: public class Car
   8: {
   9:   private readonly Engine _engine;
  10:   public Car()
  11:   {
  12:     _engine = new V6Engine();
  13:   }
  14: }
  15:  
  16: public class Program
  17: {
  18:   public static void Main()
  19:   {
  20:     // Car will always have a V6 engine.
  21:     Car car = new Car();
  22:   }
  23: }

There’s nothing “wrong” with this code. It works fine, and shows good use of polymorphism. But your Car type, by definition, will always have a V6 engine. But what happens if you need to create a car with a four-cylinder engine? You have to modify the implementation of the Car type. What if it was implemented by a third party and you don’t have the source?

Contrast the previous snippet with this one:

   1: public abstract class Engine
   2: { … }
   3:  
   4: public class V6Engine : Engine
   5: { … }
   6:  
   7: public class VTECEngine : Engine
   8: { … }
   9:  
  10: public class Car
  11: {
  12:   private readonly Engine _engine;
  13:   public Car(Engine engine)
  14:   {
  15:     _engine = engine;
  16:   }
  17: }
  18:  
  19: public class Program
  20: {
  21:   public static void Main()
  22:   {
  23:     Car v6car = new Car(new V6Engine());
  24:     Car acuraTsx = new Car(new VTECEngine());
  25:   }
  26: }

Now we can create all sorts of cars with all sorts of engines. If you’re a GoF fan, this is actually the Strategy pattern. Dependency injection (in my perspective) is basically the Strategy pattern used en masse.

However, as Jacob has pointed out, all we’ve done is pushed the requirement for creating an Engine out into the code that consumes our Car class. Jacob is 100% correct in saying that this increases your coupling. Now, instead of Car being the only type coupled to Engine, both Car and Program are essentially coupled to Engine, because to create a Car, you must first create an Engine.

This is why dependency injection frameworks like Ninject, Castle Windsor, and StructureMap exist: they fix this coupling problem by washing your code clean of the dependency resolution logic. In addition, they provide a deterministic point, in code or a mapping file, that describes how the types in your code are wired together.

This leads me to my assertion that dependency injection leads to creating loosely-coupled and highly-cohesive code. Once you start writing code that relies on a DI framework, the cost required to wire objects together falls to next to zero. As a consequence, hitting the goal of Single Responsibility becomes exponentially simpler. Put another way, you are less likely to leave cross-cutting logic in a type where it doesn’t belong. Your MessagingService needs configuration? No problem, write a ConfigurationService and add a dependency to it. Better yet, make your MessagingService dependent on an IConfigurationService interface, and then later when you’re reading configuration from a database rather than an XML file, you won’t have to go through each of your services and rewrite their configuration logic.

Jacob also asks why we don’t just use a Factory pattern (much like the provider model in ADO.NET, which he uses as an example in his article). Factory patterns are great for small implementations, but like dependency-injection-by-hand it can get extremely cumbersome in larger projects. Abstract Factories are unwieldy at best, and relying on a bunch of static Factory Methods (to steal a phrase from Bob Lee) gives your code “static cling” — static methods are the ultimate in concreteness, and make it vastly more difficult to alter your code.

I mentioned in the comment on his article that I saw the “light” when it came to dependency injection, and Jacob asked me to share the light with him. Here it is: simply put, dependency injection makes your code easier to change. That’s why it’s so popular in Agile crowds, whose whole software development practice is geared around quick alterations in path.

Is it a silver bullet? No. Is it the only way to make code easy to change? No. Is it the best way? Maybe not. But it’s the best I’ve seen so far.

More on Thread-Safe Invocation

In my last post a few days ago, I described a simple trick for creating thread-safe wrappers for event handlers in WinForms controls. I’ve discovered an even simpler approach that is much more general-purpose:

   1: public static class ThreadSafe
   2: {
   3:   public static void Invoke(ISynchronizeInvoke context, MethodInvoker method)
   4:   {
   5:     if (context.InvokeRequired)
   6:       context.Invoke(method);
   7:     else
   8:       method();
   9:   }
  10: }

Then, in your control, you can define methods like this:

   1: public class MyForm : Form
   2: {
   3:   public void SetMessage(string message)
   4:   {
   5:     ThreadSafe.Invoke(this, delegate
   6:     {
   7:       this.lblMessage.Text = message;
   8:     });
   9:   }
  10: }

Through the magic of variable capturing with anonymous methods, you don’t need to pass the arguments into your inner method (the delegate that you’re passing to the Invoke method). This also means that the Invoke method can be used to protect methods with any signature. Be aware, though, that the captured variables are read-only in the inner context. (More information about captured variables and the difference between lexical closures in C# and Ruby is available here.)

I haven’t given this too much testing so far, but it seems to work!

Thread Safe Event Handlers

I really need a full post soon, because a whole bunch of stuff is happening with Ninject (neĆ© Titan). Unfortunately (for my blog at least), we just started our first sprint for a new project that I’m leading at my day job, so at least until it stabilizes my time is going to be pretty well filled. I came up with something that seems pretty useful, though, so I wanted to share it.

There’s a rule in Windows development often jokingly referred to as The One Rule. Basically, it says that you cannot modify any part of the user interface from any threads other than the user interface thread. This is due to the way Windows handles messaging, which gets into message pumps and all sorts of other fun low-level stuff that I don’t understand enough to get into here. :) In order to create responsive user interfaces, though, we have to do most of the work in background threads. This means that eventually, the background threads will need to tell the interface to update itself to inform the user of any changes.

.NET has provided a resolution to this apparent contradiction via Control.Invoke(). The pattern typically goes like this:

   1: public class SampleForm : Form
   2: {
   3:   public SampleForm()
   4:   {
   5:     Worker worker = new Worker();
   6:     worker.ImportantEvent += HandleImportantEvent;
   7:   }
   8:  
   9:   private void HandleImportantEvent(object sender, ImportantEventArgs e)
  10:   {
  11:     if (this.InvokeRequired)
  12:     {
  13:       this.Invoke(HandleImportantEvent, sender, e);
  14:       return;
  15:     }
  16:  
  17:     // Update the user interface to show an important event happened.
  18:   }
  19: }

The block at the beginning of the event handler protects the interface from being erroneously updated by checking the control’s InvokeRequired property. If it’s true, instead of actually executing the method directly, it calls Invoke()