The following scenario came out of a discussion I was having with a fellow developer on this project. He likes to execute an Ienumerable
as soon as possible, hence why he’s doing it inside of the method. Whereas, I’m thinking that if you wait until the object is actually needed, using differed execution, you’re eliminating wasted objects in the memory.
Knowing that PricingInformation
is a List
, is my return statement consider best practice or not? Should I defer the execution to a later time? Or is it wise to ToArray()
the Select
during the return statement?
Which of these approaches do you guys think is more appropriate?
public IEnumerable<ProductPrice> GetPrices(IEnumerable<string> skus, string accountNumber)
{
if (skus.Any())
{
TesscoModel.PricingQuery priceQuery = new TesscoModel.PricingQuery();
foreach (string sku in skus)
priceQuery.Skus.Add(new TesscoModel.SkuDetail() { Sku = sku, Quantity = 1 });
priceQuery.Account = accountNumber;
TesscoModel.PricingInformationBatch pricingInfoBatch = RestHelper.PostJsonAsync<TesscoModel.PricingInformationBatch>(Settings.PricingServiceEndpoint, priceQuery).Result;
return pricingInfoBatch?.PricingInformation?.Select(pi => new ProductPrice { Sku = pi.Sku, Price = pi.OnSalePrice != default(decimal) ? pi.OnSalePrice : pi.UnitPrice, ListPrice = pi.ListPrice })?.ToArray() ?? Enumerable.Empty<ProductPrice>();
}
else
{
return Enumerable.Empty<ProductPrice>();
}
}
This method then gets called by another method inside of a helper
. Inside of which, I am using FirstOrDefault
to find the first sku
. FirstOrDefault
is again an enumerator
.
I think the differed execution is more appropriate here, because I shouldn't execute the pointer until I absolutely have to. I'm thinking that by using ToArray()
too early, I'm keeping the object on memory for too long. Even though, it might not be needed.
//Get sku Pricing in bulk
IEnumerable<ProductPrice> productPrices = productService.GetPrices(skus, (!account.IsNull()) ? account.AccountNumber : string.Empty);
foreach (var line in lines)
{
var productPrice = productPrices.FirstOrDefault(p => p.Sku.Equals(line.Sku));
line.ListPrice = productPrice?.ListPrice ?? default(decimal);
line.YourPrice = productPrice?.Price ?? default(decimal);
}