Entries
RSS 2.0

Comments
RSS 2.0

Meet the New Boss, Same as the Old Boss

I’ve decided to leave my current job at Merge Healthcare and take a position at Commercial Timesharing, where I was previously employed. A lot of things factored into my decision, but I’ve enjoyed my (brief) time here at Merge, and I have a great deal of respect for the developers and managers that I’ve worked with in my six months here. I wish them nothing but the best. I’m excited to return to CTI and work to build their .NET / business intelligence practice.

Logitech = Honorable

A few weeks back, I bought a pair of wireless Bluetooth headphones from J&R because they were on an after-Christmas sale. I read the reviews on Newegg, which said that the plastic that the band was made from was flimsy and cracked in the back after light use. “Pshaw!” I thought. “It couldn’t be that bad!” Entranced by the clearance price, I convinced myself that the people who were complaining about the headphones breaking must have been playing rugby while wearing them, and happily submitted my order.

They were very nice headphones. Then about two weeks after I got them, a crack started to develop in the headband… precisely where the rugby players had said it would! A week or so after that and my gargantuan head won the war against the plastic and they snapped enough that the wire inside of the headband broke, rendering them useless. To add insult to injury, just after I bought the original pair, Logitech released a new model that were basically the same but had a headband made of spring steel.

I called Logitech to get an RMA, and asked for them to refund my money so I could put it towards the new model. I explained I didn’t want another pair of the old model, because I felt they were clearly defective. To my surprise, the customer support rep said that they were replacing the old model with the new model free of charge. I just received my new FreePulse headphones tonight, and they’re even better than the ones I had before. (And I paid much less for them!)

It’s never good when a company creates a defective product, but Logitech has accepted the fact and acted honorably towards their customers. In this day of minimal customer support, it was a pleasant surprise. Kudos to them.

Initializing Components in the Background

The project I’m currently working on relies a lot on SOA, so we’ve got a bunch of classes that represent modularized services. Some of these services need to load some information from a database or other external sources, and rather than tying up the user interface thread, we wanted to do this initialization in the background. To solve this problem, I created an abstract base type for the services called BackgroundInitObject:

public abstract class BackgroundInitObject : IDisposable
{
  private ManualResetEvent _initEvent;
  private bool _isInitialized;

  public bool IsInitialized
  {
    get { return _isInitialized; }
  }

  public void Dispose()
  {
    Dispose(true);
    GC.SuppressFinalize(this);
  }

  protected virtual void Dispose(bool disposing)
  {
    // Ensure no threads are blocked.
    if (disposing && (_initEvent != null))
      _initEvent.Set();
  }

  ~BackgroundInitService()
  {
    Dispose(false);
  }

  protected BackgroundInitService()
  {
    _initEvent = new ManualResetEvent(false);
  }

  public void BeginInit()
  {
    ThreadPool.QueueUserWorkItem(delegate
    {
      // Initialize the service.
      Init();

      // Unblock any waiting threads.
      _initEvent.Set();

      // Set the initialized flag.
      _isInitialized = true;
    });
  }

  protected void WaitForInit()
  {
    // Block the calling thread until the service is initialized.
    _initEvent.WaitOne();
  }

  protected abstract void Init();
}

As you can see, this type uses one of the ThreadPool threads to execute the class’s initialization logic. Now, to create a class that initializes itself in the background, extend BackgroundInitObject and put your initialization logic in an implementation of the the abstract Init() method. Then, in any of your class’s public methods, be sure to start them with a call to WaitForInit(). This way, any threads that try to use the class will be blocked until it’s initialized.

For example, here’s a simple service that uses the pattern:

public class UserPreferenceService : BackgroundInitObject
{
  private Dictionary<string, string> _preferences;

  public string GetPreference(string key)
  {
    WaitForInit();
    return _preferences.ContainsKey(key) ? _preferences[key] : null;
  }

  protected override void Init()
  {
    // Load user’s preferences from a database, for example…
  }
}

The first time code that consumes the UserPreferenceService calls the GetPreference() method, if the service is still initializing, the thread will block. Once the service is initialized, calls to WaitForInit() will not block, and the service will operate as normal. You can also check to see if the service is initialized by looking at the IsInitialized property, but it’s really just for informational purposes.

One question you might be asking is, why is WaitForInit() protected and not public? The intent of this is that any thread-locking that happens should be encapsulated inside the type, and not leak into the consuming client code. If you have a compelling reason to do so, you could make it public without interfering with the rest of the pattern.

Software Engineering Joke

I’m nearing the end of Dreaming in Code by Scott Rosenberg, and it contains this gem about software engineers:

A Software Engineer, a Hardware Engineer and a Departmental Manager were on their way to a meeting. They were driving down a steep mountain road when suddenly the brakes on their car failed. The car careened almost out of control down the road, bouncing off the crash barriers, until it miraculously ground to a halt scraping along the mountainside. The car’s occupants, shaken but unhurt, now had a problem: they were stuck halfway down a mountain in a car with no brakes. What were they to do?

“I know,” said the Departmental Manager, “Let’s have a meeting, propose a Vision, formulate a Mission Statement, define some Goals, and by a process of Continuous Improvement find a solution to the Critical Problems, and we can be on our way.”

“No, no,” said the Hardware Engineer, “That will take far too long, and besides, that method has never worked before. I’ve got my Swiss Army knife with me, and in no time at all I can strip down the car’s braking system, isolate the fault, fix it, and we can be on our way.”

“Well,” said the Software Engineer, “Before we do anything, I think we should push the car back up the road and see if it happens again.”

So true. :)

Self-Referential Generics

I discovered an interesting .NET 2.0 trick recently while tinkering with one of the projects I’m working on. In practice, its usefulness is debatable, but it’s pretty cool anyways. I’ve taken to calling the trick self-referential generics. Another way to think of it is a way to “invert” type safety in a type hierarchy.

Consider a simple type hierarchy, with an abstract base type, AbstractFoo, and a concrete subtype, ConcreteFoo:

public abstract class AbstractFoo
{ ... }

public class ConcreteFoo : AbstractFoo
{ ... }

Now, let’s say that our design requires that we place our AbstractFoos in collections, and that each AbstractFoo instance needs a reference to the collection it resides in. We can accomplish this by exposing a property:

public abstract class AbstractFoo
{
  private ICollection<AbstractFoo> _collection;

  public ICollection<AbstractFoo> Collection
  {
    get { return _collection; }
    set { _collection = value; }
  }
}

Then, in our program, let’s say we want to create a collection of ConcreteFoos:

public static class Program
{
  public static void Main()
  {
    ConcreteFoo foo = new ConcreteFoo();
    Collection<ConcreteFoo> collection = new Collection<ConcreteFoo>();
    collection.Add(foo);

    foo.Collection = collection; // Error!
  }
}

Notice that we have a problem. Even though we’re creating an instance of ConcreteFoo, the property that’s exposed on it is still typed as ICollection<AbstractFoo>. If we were to then create a Collection<ConcreteFoo>, we could add the ConcreteFoo instance to it, but we couldn’t set the value of our Collection property.

The problem here is that generic type arguments are not polymorphic — that is, even though a ConcreteFoo is an AbstractFoo, and you can put ConcreteFoos into a Collection<ConcreteFoo>, a Collection<ConcreteFoo> is not a Collection<AbstractFoo>. Note that our design could feasibly require the collection to store any subtype of AbstractFoo, but in our case we’re assuming that the collection will store values that are all of the same subtype.

So what can we do? It turns out that the CLR provides us a strange feature that solves our problem. Consider the following replacement for our simple hierarchy:

public abstract class AbstractFoo<T>
  where T : AbstractFoo<T>
{ ... }

public class ConcreteFoo : AbstractFoo<ConcreteFoo>
{ ... }

Take a minute and let that type definition make sense. (It took me awhile.) Notice that because of the type constraint, the generic parameter T refers to the type AbstractFoo<T> itself, hence, it is self-referential. At first glance, it may appear that the runtime won’t be able to assure type-safety, but since all of the generic arguments are defined, it can successfully instantiate the type. Also, as you may know, the where constraint on the AbstractFoo<T> type only requires that the type T be either AbstractFoo<T> or one of its subtypes (also referred to as the Liskov Substitution Principle, or the “is-a test”).

So why in the world would we want to do such a thing? By defining the type in this manner, inside of the AbstractFoo<T> type definition, the type T refers to the current concrete subtype of AbstractFoo. Effectively, we have “inverted” the type safety, pushing up the knowledge of the concrete type from the implementation into the base types.

Knowing this, we can change our property definition in AbstractFoo<T>:

public abstract class AbstractFoo<T>
  where T : AbstractFoo<T>
{
  private ICollection<T> _collection;

  public ICollection<T> Collection
  {
    get { return _collection; }
    set { _collection = value; }
  }
}

Now, since T refers to the actual concrete type that we’re dealing with, we can do this in our application:

public static class Program
{
  public static void Main()
  {
    ConcreteFoo foo = new ConcreteFoo();
    Collection<ConcreteFoo> collection = new Collection<ConcreteFoo>();
    collection.Add(foo);
    foo.Collection = collection;
  }
}

Since the ICollection<T> exposed on AbstractFoo<T> is now typed as ICollection<ConcreteFoo> in the case of a ConcreteFoo, we can now create our Collection<ConcreteFoo> and set it directly.

Like I said, it’s not something you’ll use every day, but interesting nevertheless.