Introducing Cached
- For every line in the ShowOrders controller, the following code gets executed:
protected override void OnEnterRow()
{
new GetOrderStatistics().Run(Orders.OrderID, Items, TotalQuantity, TotalAmount);
}
- this means that for every row
- A new instance of the
GetOrderStatisticsclass is created - The Constructor for the
GetOrderStatisticsclass get's executed - The
Runmethod of theGetOrderStatisticsget's executed.
- A new instance of the
- This can be wasteful in some cases
- To avoid that, we can create the instance of the
GetOrderStatisticsclass once, and run it multiple times.
the long way
GetOrderStatistics _stats = new GetOrderStatistics();
protected override void OnEnterRow()
{
_stats.Run(Orders.OrderID, Items, TotalQuantity, TotalAmount);
}
- By following this pattern:
- The
GetOrderStatisticsclass instance is created once. - The
GetOrderStatisticsconstructor is executed once - Only the
Runmethod get's executed for each row.
- The
- Since this is such a common pattern, we decided to create a way of doing it in just one line, by using the
Cachedmethod
the short way, using Cached
protected override void OnEnterRow()
{
Cached<GetOrderStatistics>().Run(Orders.OrderID, Items, TotalQuantity, TotalAmount);
}
- The
Cachedmethod, creates an instance of theGetOrderStatisticsonly when it's used for the first time, and then simply returns the same instance, so that we can run it again and again. - Review in the output window, that the
Constructorget's executed once, while theRunmethod get's executed for each row. - Note - now we have a bug, since the values of Items, Total Quantity and Total Amount don't change for each row - we'll fix that in the next step
Help us improve, Edit this page on GitHub
or email us at info@fireflymigration.com