From the course: Advanced C#: Functional Programming Patterns

Unlock this course with a free trial

Join today to access over 24,500 courses taught by industry experts.

Reduce code side effects

Reduce code side effects

One of the principles of functional programming is to avoid side effects in pure functions. A side effect is a change in the system state or an observable interaction with the outside world, in other words, outside that function. Here's a list of things that a function should not do to avoid side effects: it shouldn't mutate shared state, it shouldn't mutate its input arguments, should not throw exceptions, and it shouldn't perform any I/O operations. Here's a simple example of mutating shared state. Up on line nine, I have an int variable _counter that's set to zero. You should already be thinking that because this is a class-level variable, it can be shared across any of the methods inside this type. And that is a flag that tells you that this is mutable across functions. So it's a problem. And you can see this simple code here in this UpdateByTwo() method is updating it by two and UpdateByFive() is updating by five. So both of those are mutating the state of that shared value. It…

Contents