The joys of Design
Lately, I’ve run into various cases in which I am so glad I designed things the way I did, for the design has let me tweak things in the code with little to no effort. The advantage of highly decoupled code is that when you require to change or refactor something in your code, the repercussions of this can be very small.
In the project I’m working on, it turned out that a COM component I’m using is STA which means that all calls to it will be performed in the same thread in which the instances were created. So even if I called a certain time consuming functionality in a background thread, if I created the instance in my main thread (where the GUI lives), it will still be affected by this call. I’m no COM expert so I found this STA peculiarity the hard way; meaning that I just saw how the GUI hanged even if I made the calls in background threads. To fix this, the effort was minimal thanks to the complete separation I had between the object creation and the logic
I originally had a factory which would create the instance of this coclass (COM class) and pass it into the constructor of each class which required it. This was the problem, because the factory would create the instance when wiring my objects and this evil STA instance would be bound to do work on the main thread. To solve the problem, I simply introduced an object pool which would make sure to have one instance of this coclass for each thread from which it’s called. This way, I would make sure that every call to the STA coclass would be done on an instance created on that same thread. Verdict: the GUI doesn’t hang anymore.
The beauty of this, is that I just added one object pool and changed the classes which held a reference to the instance of the coclass to fetch it from the object pool instead of storing it themselves. If I hadn’t design the architecture this way, I don’t know how many changes I would’ve required to solve this. And all thanks to having the architecture designed with testability in mind.