Posts

Showing posts with the label functional programming

Immutability

Last time, we looked at pure vs impure functions and we said that functional programming favors pure over impure functions. Using pure functions leads to another concept: immutability . Immutability means that a variable can only have its value set once. After that, the value never changes. So much so that in functional programming, the phrase "assigning to a variable" is often replaced by "binding to a symbol", since the word "variable" is not applicable anymore. Let's consider a non-immutable example: // Declare a class named Car public class Car { public string Color { get; set; } public bool IsStarted { get; set; } } // Instantiate a new instance var myCar = new Car { Color = "Red", IsStarted = true }; // After that, change the values of the car's properties myCar.Color = "Blue"; myCar.IsStarted = false; The properties inside of the Car class are not immutable since they can be changed after...

Pure vs Impure Functions

Image
My partner, who is also a developer, once asked me what the difference between functional and object-oriented programming is. There are many differences, and this post explores one of them: the usage of pure and impure functions. What are pure and impure functions? A pure function does not have side effects. A side effect is a change in state that happens outside of a function that gets persisted even after the function goes out of scope. Impure functions are everything else. Here are some examples to clarify. First, a pure function: // Pure int GetSum(int a, int b) { return a + b; } That is a pure function, because it does not affect any state that is outside the scope of the function. Consider this impure equivalent: // Impure int sum = 0; void ComputeSum(int a, int b) { sum = a + b; } That is an impure function, because it modifies the sum variable, and the modification persists even after the method has gone out of scope. When using an object-or...