I’m maintaining some C# 2.0 code, and the programmer uses a pattern of reading a collection of business objects by opening a DataReader and then passing it to the object’s constructor. I can’t see anything obviously wrong with this, but it feels bad to me. Is this OK to do?
private static void GetObjects()
{
List<MyObject> objects = new List<MyObject>();
string sql = "Select ...";
SqlConnection connection = GetConnection();
SqlCommand command = new SqlCommand(sql, connection);
connection.Open();
SqlDataReader reader = command.ExecuteReader(CommandBehavior.CloseConnection);
while (reader.Read())
objects.Add(new MyObject(reader));
reader.Close();
}
public MyObject(SqlDataReader reader)
{
field0 = reader.GetString(0);
field1 = reader.GetString(1);
field2 = reader.GetString(2);
}
By passing the DataReader to the object’s constructor, you establish a very tight coupling between the business object and your choice of persistence technology.
At the very least, this tight coupling will make reuse and testing difficult; at worst, it could result in the business objects knowing far too much about the database.
Resolving this isn’t too difficult – you’d simply move object initialization out of the constructor and into a distinct factory class.