Coding Horror: Spooky Breakage at a Distance

Here's a quick one from something at work last week.Code that was working just fine everywhere suddenly started to break in one environment. The code from a dispatcher function looked something like this:

void DispatchMessage(string messageType, Message m) {if (messageType == "A") { HandleA(m as MessageTypeA); }if (messageType == "B") { HandleB(m as MessageTypeB); }if (messageType == "C") { HandleC(m as MessageTypeC); }}

No problem right? (Ignore spacing / formatting in this case)The problem is that suddenly type B messages started to break. Setting a breakpoint in the function HandleB confirmed that the incoming message was null.WTF? We just checked the message type. Not only that looking at the code that calls DispatchMessage instanciates an object of the right type. A breakpoint in DispatchMessage let's us see a non-null m.So, what happened?Somewhere in a library (likely through a merge) someone included a reference to another library. That library happened to have an object in the root namespace called "MessageTypeB". The code that created the object didn't have that reference in its chain of dependency. The two classes, while named the same, are obviously different. The "as" operator, if it can't cast, doesn't throw an exception, it just returns null. Since these classes have different namespaces you wouldn't get a compile error, you just get strangeness.Takeaway: make sure all your classes are in a namespace! Otherwise you might very well get trapped in this type of pickle yourself.

Previous
Previous

Respect

Next
Next

Boberg XR9-S Theory of Operation