Loose coupling in computer systems is desirable to make components more reusable, testable and robust to changes. With tightly coupled systems, a change in one class can cause a ripple effect through other classes.
Test-ability and specifically test-ability via unit tests is a great method of verifying that your code is loosely coupled. If it’s difficult to write unit tests for each class in isolation, that is an indication that your classes may be tightly coupled to one another. In this sample I use Xunit.net for unit testing. I also use Autofac for Dependency Injection; for the purposes of this application dependency injection is very much overkill, but I’m using this as an excuse to try out Autofac.
I only used it briefly. It’s easy to get going and due to it’s intentionally minimal feature set, it’s slightly easier than other unit test formats. There are two things I dislike about it:
- Xunit.Contrib is required for Resharper support. If Xunit.Contrib is not installed, then Xunit tests are not run. It’s a minor hassle, but one I’d rather not deal with. I could see this being a nuisance in environments where multiple unit test frameworks such as mstest or nunit are used and some developers haven’t installed Xunit.Contrib. Developers missing the Xunit.Contrib library may not realized they’re not running all the tests. This is really a small issue, but it is something I have not encountered with mstest and nunit.
- Xunit uses [Fact] to denote tests instead of [Test] attributes. At a purely subjective level I don’t like this. I think of unit tests as a serious of tests against a class. I don’t think of my tests as Facts about my code. I don’t like it.
Autofac is straightforward to use. It has good documentation and took no time to get up and running. Several sites have touted it’s excellent performance. I have not verified those claims… I have also never found IoC containers to be performance bottlenecks.
I won’t cover performance here, but instead I’ll refer to the following good blog which covers .Net IoC performance:
As a demonstration of loose coupling I have expanded on my early article using Thrift. I have created a C# Thrift Client application and tried to minimize the dependency on Thrift by using an Adapter class. This keeps the business logic, in this case the Sum class, completely separate from the Thrift code.