MANAGING SIDE EFFECTS

In spite of the help provided by libraries such as Parallel Extensions, you still need to do a lot of potentially complex structural work on your codebase in order to parallelize it. In functional programming, the kind of data access where multiple methods or functions in a program have shared access to the same data — most importantly write access to that data — is called a side effect. One of the main ideas of functional programming is to manage such side effects. This may mean to prevent them, and it is certainly a target to reduce these side effects to begin with, because that makes the remaining ones easier to manage. It is an illusion, however, that a computer program could do anything useful without having side effects in the technical sense — whenever something is seen on screen, data is stored in a file or a database, or something is sent over a network, that is, on some level, a side effect.

The imperative reaction to the problem of shared data access is typically to impose restrictions, with the technical term being synchronization. This is often summarized as mutual exclusion, which describes the idea very well: while one execution thread accesses a particular piece of information to make a change, others can’t do so at the same time. It’s a simple and efficient concept, but quite hard to get right. As soon as there are many pieces of information, as there are bound to be in imperative applications, the individual critical sections tend to overlap ...

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.