Friday, January 11, 2008

Encapsulate complicated or generic code

Whenever you come across code that is more complex or generic than it needs to be try to refactor it. However it may not be possible to do this in some cases. When that happens just wrap the complex code with your own class that has the interface that you wished you had to work with.

Here is an example

The following code calls gateway.GetProducts(criteria) to return an array of products. Notice that most of the code below is just used to set up the criteria object.


ICriterion salesDateCriterion = new SalesDateCriterion(newstring[]{uploadDate.ToString()},
OperationEnum.Equal);
ICriterion prodLineIdCriterion = new ProdLineIdCriterion(new string[]
{productionLineId.ToString()},OperationEnum.Equal);
ICriterion productNoCriterion = new ProductNoCriterion(productNo.ToString(),
OperationEnum.Equal);
ICriterion[] criteria = new ICriterion[] {salesDateCriterion, prodLineIdCriterion,
productNoCriterion};

IProduct[] products = gateway.GetProducts(criteria);

if (products.Length != 1 || products[0] == null)
throw new Exception("Product not found");

return products[0];



For my application I did not need the power that criteria gave me I only needed to find a single product by uploadDate, productionLineId and productNo. So I just wrapped the above code in a method called GetProduct. Now the client code now contains a single line of code that is much easier to understand.

public IProduct GetProduct(UploadDate, productionLine,productNo)

In the newly created class I also added two similar methods GetVariety and GetOrder.

public IVariety GetVariety(int varietyNo)
public IOrder GetOrder(DateTime uploadDate, int productionLineId, int productNo)

1 comment:

Pauline said...

Thanks for writing this.