Skip to main content

Improving “Boiler Plate” Data-Reader Code – Part 2

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.

namespace DataAccess.Example
{
using System.Data;
using System.Data.BoilerPlater;

public class CustomerDRConvertorPart2 : IConvertDataReader<Customer>
{
private int idIndex = -1;
private int firstNameIndex = -1;
private int surnameIndex = -1;

public Customer Parse(IDataReader dataReader)
{
if (idIndex == -1)
{
idIndex = dataReader.GetOrdinal("Id");
firstNameIndex = dataReader.GetOrdinal("FirstName");
surnameIndex = dataReader.GetOrdinal("Surname");
}

return new Customer
{
Id = dataReader.GetGuid(idIndex),
FirstName = dataReader.GetString(firstNameIndex),
Surname = dataReader.GetString(surnameIndex)
};
}
}
}

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.

namespace DataAccess.Example.Tests
{
using System;
using System.Data;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using NUnit.Framework;
using Moq;
using Assert = NUnit.Framework.Assert;

[TestClass]
public class CustomerDRConvertorPart2Tests
{
[TestMethod]
public void CustomerDRConvertor_GoodCall()
{

var dataReader = new Mock<IDataReader>();

dataReader.Setup(dr=>dr.GetOrdinal("Id")).Returns(1);
dataReader.Setup(dr=>dr.GetOrdinal("FirstName")).Returns(2);
dataReader.Setup(dr=>dr.GetOrdinal("Surname")).Returns(3);

var id = Guid.NewGuid();
const string firstName = "John";
const string surname = "Doe";

dataReader.Setup(dr=>dr.GetGuid(1)).Returns(id);
dataReader.Setup(dr=>dr.GetString(2)).Returns(firstName);
dataReader.Setup(dr=>dr.GetString(3)).Returns(surname);

var convertor = new CustomerDRConvertorPart2();

var customer = convertor.Parse(dataReader.Object);

Assert.That(customer.Id, Is.EqualTo(id));
Assert.That(customer.FirstName, Is.EqualTo(firstName));
Assert.That(customer.Surname, Is.EqualTo(surname));

dataReader.Verify(dr=>dr.GetOrdinal(It.IsAny<string>()), Times.Exactly(3));
dataReader.Verify(dr=>dr.GetOrdinal("Id"), Times.Once());
dataReader.Verify(dr=>dr.GetOrdinal("FirstName"), Times.Once());
dataReader.Verify(dr=>dr.GetOrdinal("Surname"), Times.Once());

dataReader.Verify(dr=>dr.GetGuid(It.IsAny<int>()), Times.Once());
dataReader.Verify(dr=>dr.GetGuid(1), Times.Once());

dataReader.Verify(dr=>dr.GetString(It.IsAny<int>()), Times.Exactly(3));
dataReader.Verify(dr=>dr.GetString(2), Times.Once());
dataReader.Verify(dr=>dr.GetString(3), Times.Once());

convertor.Parse(dataReader.Object);

dataReader.Verify(dr=>dr.GetOrdinal(It.IsAny<string>()), Times.Exactly(3));
dataReader.Verify(dr=>dr.GetOrdinal("Id"), Times.Once());
dataReader.Verify(dr=>dr.GetOrdinal("FirstName"), Times.Once());
dataReader.Verify(dr=>dr.GetOrdinal("Surname"), Times.Once());

dataReader.Verify(dr=>dr.GetGuid(It.IsAny<int>()), Times.Exactly(2));
dataReader.Verify(dr=>dr.GetGuid(1), Times.Exactly(2));

dataReader.Verify(dr=>dr.GetString(It.IsAny<int>()), Times.Exactly(4));
dataReader.Verify(dr=>dr.GetString(2), Times.Exactly(2));
dataReader.Verify(dr=>dr.GetString(3), Times.Exactly(2));
}
}
}

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.

Comments

  1. I've finally got around to adding part 3, have updated this post with a link to it.

    ReplyDelete

Post a Comment

Popular posts from this blog

Why do my Android Notification only appear in the status bar?

I'm definitely getting back into Android development, I'm remembering that feeling of 'Surely this should be easier than this!'. All I wanted to do was to schedule a local notification which behaved similar to a push notification pop-up. That is, as well as showing the small icon in the status bar I wanted it to pop up on screen to notify the end user. All seems fairly easily, I found this code for how to schedule a notification. That all worked perfectly, apart from the notification would only appear in the status bar. Searching around I found loads of different answers / solutions, mostly all saying the same thing:It only worked if you used 'NotificationCompat.Builder' in place of 'Notification.Builder', orYou had to set the priority to 'NotificationCompat.PRIORITY_HIGH'As usually happens, none of these solutions worked for me until I added in the missing piece of the jigsaw:- '.setDefaults(Notification.DEFAULT_ALL)'. For me this…

Do "Task Hours" add anything in Scrum (Agile)?

What do task hours add to the overall process in scrum?This was a question that has arisen from all team members in both instances that I've helped teams switch over to scrum. The benefits of artifacts like the comparative story point estimation, the 2 week sprints, stand-ups and the end of sprint demo have been self evident to the team, but as one I think every team member has expressed dismay when it comes to task planning and estimating each task in hours. Left unchecked there is a natural tendency for people to actually begin to dread the start of each sprint purely due to the task planning session.In my current role we've been lucky to investigate this further as a team.The team sat down to discuss the problems it was experiencing with estimating tasks in hours and the following common themes appeared:It is hard: Maybe it shouldn't be, but time estimation is hard! Story points are comparative and abstracted making them easier to determine, but time estimate is gen…

IPhone hangs when running from XCode

I've had this happen a couple of times now and the first time was a little worrying that I'd bricked my iPhone. Basically I was running an application on my phone via XCode and when rebuilding an updated version it failed with a "busy" error message. Stopping XCode and unconnecting my phone had no effect, the phone was stuck displaying the loading screen of the application and wouldn't respond to any key commands. To fix you have to hard reboot, holding the power and home button until the phone reboots - doesn't lose any of the data you have on your phone (a concern the first time I did it).