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.
Don't mutate input arguments - C# Tutorial
From the course: Advanced C#: Functional Programming Patterns
Don't mutate input arguments
We have to remember, you don't want to mutate the input arguments; otherwise, you've got a side effect. Let me show you how that could happen. Remember this code from the previous example? I have the shared state here. This list of ints of the odd numbers, and then when I called AddNumbersToList(), I added these two numbers. So following this new principle of where we pass in the list, I can still run into issues. Here, I refactored my code. Now I have an AddNumbersToList() that takes a list of int as the input, and the total of the numbers now takes the list as input. This one is still pure because it's just for reaching over that input list passed in and returning the total. But look what's happening here. I'm passing in a list of int and I'm adding two items to it. So this is a side effect. So just like the last example, if I check the count of the list before I call AddNumbers, it's going to be lower than after I call AddNumbersToList(). So don't mutate the input state.
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)
-
-
-
-
-
-
-
-
-