Skip to content

Instantly share code, notes, and snippets.

@asarnaout
Last active September 28, 2018 03:09
Show Gist options
  • Save asarnaout/6567489a88410080ecb2619afe730ad1 to your computer and use it in GitHub Desktop.
Save asarnaout/6567489a88410080ecb2619afe730ad1 to your computer and use it in GitHub Desktop.
Side Effect Free Functions
public class CartService
{
public decimal GetShippingQuoteForUpdatedAddress(ShoppingCart cart,
Address updatedAddress)
{
cart.CalculateShippingDetail(updatedAddress); //Side effect
return cart.ShippingQuote;
}
}
public class ShoppingCart : IEntity
{
public string ShoppingCartCode { get; }
public IEnumerable<string> Products { get; set; }
public decimal ShippingQuote { get; private set; }
public string ShippingMethod { get; private set; }
public void CalculateShippingDetail(Address customerAddress)
{
//Some Complex Calculations here that cause a side effect
ShippingQuote = 20.3m;
ShippingMethod = "Next Day Air";
}
}
public class ShippingDetail //Refactoring the ShippingDetail to a value object
{
public ShippingDetail(decimal shippingQuote, string shippingMethod)
{
ShippingQuote = shippingQuote;
ShippingMethod = shippingMethod;
}
public decimal ShippingQuote { get; private set; }
public string ShippingMethod { get; private set; }
public ShippingDetail Calculate(Address customerAddress,
IEnumerable<string> Products)
{
//Some Complex Calculations here
return new ShippingDetail(20.3m, "Next Day Air");
}
}
public class ShoppingCart : IEntity
{
public string ShoppingCartCode { get; }
public IEnumerable<string> Products { get; set; }
public ShippingDetail ShippingDetail { get; set; }
public void CalculateShippingDetail(Address customerAddress)
{
ShippingDetail = ShippingDetail.Calculate(customerAddress, Products);
}
}
public class CartService
{
public decimal GetShippingQuoteForUpdatedAddress(ShoppingCart cart,
Address updatedAddress)
{
var detail = cart.ShippingDetail.Calculate(updatedAddress, cart.Products);
return detail.ShippingQuote;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment