Special cases in code that are workarounds for a seemingly innocuous problem are almost always a symptom of something wrong in your design.
Here’s an example from some work that I’ve been doing for the past couple of days: identifying layering violations in RubyCLR. This work led me to look at how I was caching Type objects in the bridge.
I currently hold onto a reference to a CLR Type object in each Ruby shadow class object that I create. So you could think of the Ruby type system as a cache for all Type objects that are currently in use by your program.
The problem is this: I cache Type objects elsewhere as well, particularly in the lower levels of the bridge that use my RbDynamicMethod library. Now, it just doesn’t feel right to have duplicate caches, so I set about redesigning my Reflection engine to use a unified cache.
While looking at the C++ code that I had to refactor, I decided to postpone this work to work on something more important: leveraging inheritance in my Ruby shadow class objects. Right now, if you had a System.Windows.Forms.TextBox and a System.Windows.Forms.Button you will have duplicate accessor Name accessor methods; my shadow classes were completely ignorant of inheritance in the CLR class libraries. The correct solution is to attach the Name accessor method shim to the class where it was defined: the common System.Windows.Forms.Control class.
Postponing the work seemed like the right thing – after all, I was just being inefficient, right?
So I started to implement ruby shadow class inheritance. But then I ran smack into a what was now a clear layering violation: the reference to the Type object that I was holding in my shadow class objects. There was even (surprise!) some special case code to treat Type objects differently.
I need to move that reference out of the Ruby shadow class object and into the unified Type cache that I wanted to implement earlier, but postponed!
So the moral of the story is this: several seemingly unrelated problems were all symptoms of the same incorrect design. I’m continually amazed at how refactoring code almost always leads me to a (more) correct design.
As an aside, this is also why programming languages that let you write fewer lines of code are almost always superior: it’s just easier to see the incorrect design when you’re staring at fewer lines of code to begin with. And they also have the side-effect of making it much easier to do complex refactoring because there’s less language-related bookkeeping to do …. hmmm I wonder what languages I’m comparing here? :)