Dependency Injection and Abstract Interfaces in C#

If you’ve ever written code, you’ve probably written a unit test.  If you haven’t written unit tests, you should start.

Now.

Really.

Unit tests let you quickly verify that your code is operating in a predictable fashion.  When you make changes down the road, you re-run the same unit tests to make sure nothing broke.

In many cases, you write the unit tests first.  Define what your code will do, decide what objects you will use/make to accomplish that, then write a test.  At this stage, the test will fail – but you have a place to start.  Now write your code until it passes the test and you can be certain your code, however inelegant it might be, is doing what you expect.

Sometimes, though, you don’t write the unit tests first.  You go back days, weeks, even years later and try to add unit tests to your code.  In most cases, this will be next to impossible because of the way the code is written.  A function with direct calls to the database needs to be rewritten.  File access needs to be abstracted into an object.

It’s tricky, but makes your code more maintainable in the long run.
[Read more…]