Thursday, 16 February 2012

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

In part 3 we created a SQL repository object that took a populated instance of IQuery to select/return an enumerable list of objects. A limitation of the repository was that the query had to be text based, it couldn't handle stored procedures and/or parameters. By incorporating an abstract factory pattern we can extend the functionality to handle different types of query.

The original code inside "SqlRepository.Get(...)" needs to be changed from:

using (var command = connection.CreateCommand())
{
command.CommandText = query.Text;
 
connection.Open();

To:

using (var command = connection.CreateCommand())
{
var handler = QueryHandlerFactory.Create(query);
handler.Assign(command, query);
 
connection.Open();

The static factory class takes an instance of IQuery and determines which "query handler" to return depending upon the additional interface that the "passed in" query implements. This is implemented via the following code:

public static class QueryHandlerFactory
{
public static IHandleAQuery Create(IQuery query)
{
if (query is IDefineCommmandTextQuery)
{
return new HandleCommandTextQuery();
}
 
var ex = new NotSupportedException();
ex.Data.Add("IQuery Type", query.GetType());
throw ex;
}
}

To finish off the implementation the following new interfaces and code are needed:

public interface IDefineCommmandTextQuery : IQuery
{
string Text { get; }
}
 
public interface IHandleAQuery
{
void Assign(SqlCommand command, IQuery query);
}
 
public class HandleCommandTextQuery : IHandleAQuery
{
public void Assign(SqlCommand command, IQuery query)
{
command.CommandType = CommandType.Text;
command.CommandText = ((IDefineCommmandTextQuery)query).Text;
}
}

Finally we simplify the IQuery interface as it's only property has now been moved up into IDefineCommandTextQuery and then update all concrete implementations of "IQuery" to "IDefineCommandTextQuery " as well, without these final changes the factory class will not be able to correctly determine the handler from the interface that is implemented.

public interface IQuery
{
}
 
public class GetAllCustomersQuery : IDefineCommmandTextQuery
{
public string Text
{
get
{
return "SELECT id, Firstname, Surname FROM Customer";
}
}
}

Now our code can be safely extended to handle different query types just be creating the new implementation of the query handler and modifying the factory to handle the identification and creation of the new type. Part 5 will show how this functionality can be extended to handle stored procedures with parameters.

No comments:

Post a Comment