Refactoring - which template to use in this example?

I have a function that processes strings from an excel file. In this function, I have a for.Now loop, after the line is retrieved, we check various conditions. If any condition is false, we continue with the next row. Can this code be made more structured using a template?

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); 
+4
source share
4 answers

You can use a style template where there is a series of classes, each of which is responsible for checking one aspect of reality and reporting the type of error.

you will pass your Prod first class, which will check the correctness; if it was invalid, it will report and return false. if it was valid, it would return a validation check for the successor of the current instance (if it was one).

then your code could just get Prod and pass it to root authentication and continue if it reports an error.

It will also allow you to easily add new validators in the future, potentially being able to do this without recompiling, depending on how you implemented the chain of validators.

something like this: (pseudocode, not verified / compiled)

 public interface IValidator { bool IsValid(Product product); IValidator Successor{get;set;}; } public class AbstractValidator : IValidator { IValidator m_successor=null; public abstract bool IsValid(Product product); IValidator Successor { get { if(m_sucessor==null) return new AlwaysValidSuccessor(); else return m_successor; } set { m_successor=value; } } } public class NullValidator : AbstractValidator { public bool IsValid(Product product) { if (product!=null) { return Successor.IsValid(product); } return false; } } public class ExpiredValidator : AbstractValidator { public bool IsValid(Product product) { if (product.Expired==false) //whatever you need to do here { return Successor.IsValid(product); } return false; } } 

then you use it:

 IValidator validatorRoot = new NullValidator(); validatorRoot.Successor = new ExpiredValidator(); // construct the chain with as many as you need //then use it if (validatorRoot.IsValid(Prod)==false) { continue; } 
+2
source

The best way to fix this is to define your queries so that they do not return invalid or outdated products.

+1
source

Can you use a switch housing instead?

0
source

In conjunction with Sam Holder, discarding how versatile you need this verification system, you can wrap any of the duties with Decorator to enable validation verification with a common behavior that is a joint more than one verification verification.

0
source

All Articles