Have a look at the below code to Load a List
while (dataReader.Read())
{
City city;
if (City.TryLoad(dataReader, out city))
{
defaultCities.Add(city);
}
}
TryLoad reads the reader and loads the dataobject and retur开发者_运维问答ns true when successful and false when unsuccessful. The benefit of this, I was told, was that the code would not throw an error if the code fails for some reason when loading the object. So if one row of data is corrupt, then that is not added to the default connection. Moreover, in the try load we can log which particular row threw and error and fix that.
On the other hand the approach which I followed earlier was simply loading the objects and adding them to the collection.
while (dataReader.Read())
{
City city = new City();
city.Name = reader["Name"].ToString();
.
.
defaultCities.Add(city)
}
While the second approach may fail due to corrupt value in the database, wouldn't you want that? Wont catching bugs due to a missing value become difficult in the first approach?
Just wanted the opinion of others on the pros cons of the two approaches.
Also, please help in tagging the question appropriately.
If you can permit an exception to be thrown on bad data, the second approach is best. This is common in situations where the administrators have control of the quality of the data.
However, it's often true that the administrators can't guarantee the quality of the data. In these cases, it's frequently a requirement that the application handle malformed data gracefully. When faced with this need, the first approach is an elegant way to do that.
You're quite right, if there's something wrong with the data I would want to know asap as well.
I personally use the second approach, though automated with a small app I wrote to generate my BLL for me.
The second. I like it as its much cleaner and easier to maintain.
You can also load data straight out of the data reader into variables and test before loading into your classes - DateTimes are good examples, I'd suggest using TryParse() on them:
DateTime contentLastModified;
if (!DateTime.TryParse(dr["LastModified"].ToString(), out contentLastModified))
{
contentLastModified = MyApp.Common.Constants.SystemTypeValues.NullDate;
}
精彩评论