I have a function which is processing rows from an excel file.In this function,I have a for loop.Now,once a row is extracted,we check for various conditions.If any condition is false,we continue with next row.Can this code be made more structured using a pattern?
foreach (System.Data.DataRow dr in ds.Tables[0].Rows)
{
Product prod = GetProduct(dr);
if (prod == null)
{
IndicateNotInserted(dr, "InvalidProduct");
continue;
}
if (IsProductExpired())
{
IndicateNotInserted(dr, "Expired");
continue;
}
ProcessRow(dr);
You could use a chain of responsibility style pattern where a there are a series of classes each one responsible for checking one aspect of validity and reporting the type of error.
you would pass your
Prodto the first class which would check the validity, if it was invalid it would report and return false. if it was valid it would return the validity check of the successor of the current instance (if it had one).then your code could just get the
Prodand pass it to the root validity checker and continue if it reported false.This would also allow you to easily add new validators in the future, potentially being able to do it without having to recompile, depending on how you implemented the construction of the chain of validators.
something like this: (pseudo code, not tested/compiled)
then you use it: