As of now, we have two different styles of object intializations based on SQL row in our codebase:
public Config(SqlDataReader sdr) {
for (int i = 0; i < sdr.FieldCount; i++) if (!sdr.IsDBNull(i)) {
switch (sdr.GetName(i)) {
case 'Id': Id = sdr.GetInt32(i); break;
...
}
}
}
and
public User(SqlDataReader sdr)
{
UserId = sdr.GetInt32(0);
if (!sdr.IsDBNull(1)) Name = sdr.GetString(1);
...
}
They are called like this:
while(sdr.Read()) users.Add(new User(sdr));
C# coding guide says that style should be consistent, so one of them has to change to the other, if we don't find a reason to keep them different. So, before we implement the whole project with its 50+ models, we need a design guideline regarding this.
Both designs have their drawbacks, but I don't know how to make it better:
- In the first, no one will notice until later in the code if required fields are dropped from the query.
- The second one will fail whenever the fields in the query are reordered.
Which one should we prefer, or how could we improve them to address the drawbacks? Are they really drawbacks, in terms of code maintenance/reuse?