In Part 1 of this series we started with a basic Data-Reader / SQL Connection/Command pattern and illustrated how it is possible to abstract the parsing of the Data Reader into a standalone object that can be fully unit tested in isolation of the calling code. In Part two of the series we will highlight a very simple optimisation that can be made to the “DataReader” convertor and the required update to the tests to capture/verify the changes. In this revision the original “CustomerDRConvertor” has been updated to include extremely basic caching, which for the duration of the object’s existence should ensure that only the first call needs to reference the “GetOrdinal(…)” method to find the element index of each desired column. Subsequent calls can then use this “cached” index to reference the column by position rather than name.
In traditional ASP applications (back in the day) the above caching pattern used to result in reasonable performance gains. I’ve not looked into the benefits within a modern day .NET application and in some instances could be classed as premature optimisation. But for the purpose of this example it provides a perfect illustration as to how the abstracting the data reader parsing from the connection/command code can provide many benefits. Updated objects can be developed and tested in complete isolation of the existing code and then plugged into the code base with only minimal changes.
This updated code can be verified using the unit test below. In the test the “Parse(…)” method is called once and the mocked objects are verified that they were called correctly. The “Parse(…)” method is then called again and the mocked objects verified to make sure that the second call only resulted in an additional call to the GetGuid(…) and GetString(…) methods. Due to the very basic caching that was implemented there is no need for the second call to make any GetOrdinal(…) references, which the verification of the mocked objects can confirm. The tests verify the expected behaviour, not the inner workings of any implementation of a DataReader object.
In part three of this series I will cover how the above code can be moved into an abstract base class for data access that all inheriting classes can utilise through interfaces and generics.
Part 3 builds on the code developed in parts 1 & 2 into a usable solution.