Tuesday, March 23, 2010

Isolation from database

So I'm working on a legacy project and quite intent to re-factor the heck out of it. One of my goals was to make the code testable and to do that I had to rip out the dependency on the database/DataSet implementation.

To do this I created a data provider class and then implemented an iterator block and used the yield statement.

public override IEnumerable MyDataObjects
{
get
{
using (var connection = new SqlConnection(ConnectionString))
{
connection.Open();
using (var command = new SqlCommand{CommandText = "...", Connection = connection })
{
using (var reader = command.ExecuteReader())
{
while (reader != null && reader.Read())
{
yield return new MyDataObject
{
//extract the column values
};
}
}
}
}
}
}


Now the consumer of the data doesn't know where the data is coming from and that's just fine!

foreach(var myData in provider.MyDataObjects)
{
//do stuff with the object
}