Interface Data Type to the Rescue

Posted by: Jonathan Horvath 7 years, 5 months ago

I'm always amaze the range of software development problems that the Interface data type can solve. Anytime there is need to refactor code, the first thing that typically needs to be accomplished is extract interfaces from classes. Once the dependent classes are referenced by interfaces, they can be mocked and unit testing is possible. While performing the extraction of interfaces on legacy code, I found a useful side benefit.

I was attempting to add unit test for a particular C# class. I found it odd that a particular class would determine the type of an object using the 'as' keyword. The use of keyword 'as' in C# signals a possible design issue. The 'as' keyword determines the type of an object at runtime. There is little sense in doing the type checking at runtime when all the code is contained within a strongly typed language. As a general rule, I always try to leverage the ability of the compiler to ensure code correctness. I quickly realized that the 'as' keyword was used because the class's assembly could not be reference. The assembly was already referenced by the assembly with the class implementation. Creating a reference back to the assembly would cause a circular reference. Interface to the rescue! A short term fix is to create a interface to the class in the dependent assembly. This avoided the usage of the 'as' class. Now the class looses it's dependency on the class implementation and it can be mocked.