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 - C# Tutorial
From the course: Advanced C#: Functional Programming Patterns
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
-
-
-
-
(Locked)
Function categories3m 18s
-
(Locked)
Write pure functions for better code3m 52s
-
(Locked)
Example of an impure function1m 39s
-
(Locked)
Refactor impure function to pure2m 21s
-
(Locked)
Reduce code side effects2m 18s
-
(Locked)
Refactor side effect example1m 4s
-
(Locked)
Don't mutate input arguments1m 8s
-
Use an immutable argument3m 41s
-
(Locked)
What about impure class properties3m 26s
-
(Locked)
-
-
-
-
-
-
-
-
-