The interesting thing about the test in this example is that an assumption is made: “while the process of calculating the MutableOrderLine value is in progress, the values of MutableProduct.Price and MutableOrderLine.Count are not going to change.” Within the context of this simple test, the assumption is correct, but outside such an artificial context, this cannot easily be guaranteed. The data structures are declared in such a way that the data contained within them could change at any time. Of course this can only happen in reality if the data is shared across threads running in parallel. In Microsoft’s documentation of .NET Framework data types, there is a section that states whether each data type is to be regarded thread safe or not. The data structures that are marked thread safe usually use locking or other access protection/coordination mechanisms to prevent conflicting access.
In the example scenario, the data that is assumed to be consistent throughout the unit of work represented by the GetValue function lives in two different objects. The objects themselves could theoretically implement locking on their individual properties, but that wouldn’t be sufficient. This algorithm would need locking on the function level, acquiring two separate locks before going about its business of calculating the result. Or perhaps it wouldn’t matter whether the old or the new value of a simple field like Count is being used. The scenario certainly shows the issues that ...
Get Functional Programming in C#: Classic Programming Techniques for Modern Projects now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.