mardi 28 août 2018

Filters Design Pattern

I really like the 'filters' in ASP.MVC. They are briliant.

I would like to use somekind of filter design pattern for my business logic.

Consider the following:

var shippingFilterCost = {
  "Name": "CalculateShippingCostsFilter",
  "InjectedServices": "product, shoppingBasket, CalculateProductShipping",
  "MainMethod": function (product, shoppingBasket,CalculateProductShipping) {
    var shippingCost = CalculateProductShipping(product.weight, shoppingBasket.locationToShipTo);
    product.ShippingCost = shippingCost;
    return product;
  }
}


var checkIfBuyerHasAVouche = {
  "Name": "CheckVoucher",
  "InjectedServices": "product, shoppingBasket, CheckVoucherValid,CalculateVoucher",
  "EntryCondition": function (product, shoppingBasket, CheckVoucherValid, CalculateVoucher) {
    var isVoucherValid = CheckVoucherValid(shoppingBasket.voucherCode);   
    return isVoucherValid;
    // we only go to the 'MainMethod' if entryCondition returns true;
  },
  "MainMethod": function (product, shoppingBasket, CheckVoucherValid, CalculateVoucher) {
    var voucherPrice = CalculateVoucher(shoppingBasket.voucherCode);
    product.voucherPriceReduction = voucherPrice;
    return product;
  }
}

So we will have a base product, and that base product will go through those 2 filters that will add 'information to it'.

One filter calculates shipping cost and another the voucher.

Advantages:

1) We can easily see what 'services' are used where by their references.

2) We can easily track what method mutates what property with ease because

3) The services are just pure methods that return something.

4) All the mutations are centralized inside mainMethod

5) We also have 'EntryCondition' method we can separate and see what filters runs and what filter does not.

I am not sure how better to explain what is happening here. Obviously this logic is very simple but if i had multiple suppliers, customer types and so on, each with their own logic we can see how this declarative way can help me out.

If you have a better idea how can I explain this better, please edit my post.

Aucun commentaire:

Enregistrer un commentaire