Skip to content

Commit 412786d

Browse files
committed
Add a post about imperative vs functional vs FRP
1 parent 2ed8ea4 commit 412786d

4 files changed

Lines changed: 219 additions & 0 deletions

File tree

Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
{{< quizdown >}}
2+
3+
---
4+
primary_color: green
5+
secondary_color: lightgray
6+
text_color: black
7+
shuffle_questions: false
8+
shuffle_answers: true
9+
---
10+
11+
# What is functional programming about?
12+
13+
1. [ ] Writing functions that may modify state as needed
14+
1. [x] Avoiding side effects and state mutation
15+
1. [ ] Relying on side effects to manage state transitions
16+
1. [ ] Emphasizing object-oriented design patterns
17+
18+
# In functional programming, why must functions avoid side effects?
19+
20+
1. [ ] To improve performance
21+
1. [x] To prevent unpredictable state changes
22+
1. [ ] To enable state mutation
23+
1. [ ] To allow recursion
24+
25+
# Which paradigm describes a sequence of instructions that modify the program’s state step by step?
26+
27+
1. [ ] Functional
28+
1. [ ] Functional Reactive
29+
1. [x] Imperative
30+
1. [ ] Declarative
31+
32+
# What is considered a side effect in a function?
33+
34+
1. [ ] Returning a computed value
35+
1. [x] Modifying a variable outside its scope
36+
1. [ ] Calling another pure function
37+
1. [ ] Using recursion
38+
39+
# How is state typically managed in functional programming?
40+
41+
1. [ ] By mutating global variables
42+
1. [x] By transforming old state into new state
43+
1. [ ] By ignoring state changes
44+
1. [ ] By centralizing state in a single object
45+
46+
# Which pattern is used by functional reactive programming?
47+
48+
1. [ ] Singleton
49+
1. [ ] Factory
50+
1. [ ] Delegate and Callback
51+
1. [x] Publisher and Subscriber
52+
53+
# What is the primary benefit of using pure functions?
54+
55+
1. [ ] They allow state mutations
56+
1. [x] They are easier to test and debug
57+
1. [ ] They increase code complexity
58+
1. [ ] They require global variables
59+
60+
# Examine the code below. Does it fully follow the functional programming principles?
61+
62+
```swift
63+
var value = 0
64+
65+
func increment(_ value: Int) -> Int {
66+
value + 1
67+
}
68+
69+
value = increment(value)
70+
print(value)
71+
```
72+
1. [ ] Yes, it's correct
73+
1. [ ] No, the function has side effects
74+
1. [x] No, it mutates state by reassigning a mutable variable
75+
1. [ ] No, it mutates the "value" variable inside the increment function
76+
77+
{{< /quizdown >}}
65.4 KB
Loading
Lines changed: 141 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,141 @@
1+
---
2+
title: 'Imperative, Functional, Functional Reactive: Do you know the difference?'
3+
date: 2025-02-16
4+
tags: ['Swift', 'Combine', 'Functional Reactive Programming']
5+
cover:
6+
image: 'images/cover.png'
7+
alt: 'Do You Know the Difference Between Imperative, Functional, and Reactive Programming?'
8+
---
9+
10+
# Paradigms
11+
12+
## Imperative
13+
14+
In the imperative approach, we have a sequence of instructions that describe step by step how the program's state is modified.
15+
16+
Let's look on the example ⤵️
17+
18+
```swift
19+
var value = 0
20+
21+
func increment() {
22+
value += 1 // Mutating the state
23+
}
24+
25+
print(value) // 0
26+
increment()
27+
print(value) // 1
28+
```
29+
In the code we have a mutable variable `value` and a function `increment` that mutates the state (`value`). We first print the initial value, then increment it, and finally print the updated value.
30+
31+
Simple, right? Let's jump into functional programming!
32+
33+
## Functional
34+
35+
What is functional programming? Is it only about writing functions? 🤔
36+
37+
Not really.
38+
39+
Of course, functions are a foundation of functional programming, but they need to follow an important rule ⤵️
40+
41+
In functional programming, functions must not have side effects.
42+
43+
What's the side effect? - A side effect occurs when a function modifies any state outside of its own scope.
44+
45+
Looking at the imperative programming example, we can clearly see a side effect inside the increment function ⤵️
46+
47+
```swift {hl_lines=[4]}
48+
var value = 0
49+
50+
func increment() {
51+
value += 1 // Mutating the state (Side effect)
52+
}
53+
54+
print(value) // 0
55+
increment()
56+
print(value) // 1
57+
```
58+
59+
How can we re-shape this code to align with functional programming principles? - we need to get rid of state mutation both from main program flow and inside the `increment` function.
60+
61+
Let's fix the function first by passing the state (`value`) as an argument and returning the result of the operation as function's output.
62+
63+
```swift
64+
var value = 0
65+
66+
func increment(_ value: Int) -> Int {
67+
value + 1
68+
}
69+
70+
print(value) // 0
71+
value = increment(value)
72+
print(value) // 1
73+
```
74+
75+
Now, `increment` is a pure function. It returns a new state by adding 1 to the input without mutating any external state. To manage state changes in functional programming, we create new values instead of modifying the old state.
76+
77+
Having pure functions always returning the same output for a given input makes them easier to test and debug.
78+
79+
Now we focus on mutability which functional programming aims to avoid. Instead of mutating the state - `value`, we transform the old state and return a new one.
80+
81+
The code refactored to the functional form ⤵️
82+
83+
```swift
84+
func increment(_ value: Int) -> Int {
85+
value + 1
86+
}
87+
88+
let initialState = 0
89+
let incrementedState = increment(initialState)
90+
91+
print(initialState) // 0
92+
print(incrementedState) // 1
93+
```
94+
95+
By adding the `increment` method as an extension to `Int`, we can use method chaining to apply multiple transformations in a clean, readable way. This is a common practice in functional programming, known as function or method composition ⤵️
96+
97+
```swift
98+
extension Int {
99+
func increment() -> Int {
100+
self + 1
101+
}
102+
}
103+
104+
let initialState = 0
105+
let incrementedState = initialState
106+
.increment()
107+
.increment()
108+
109+
print(initialState) // 0
110+
print(incrementedState) // 2
111+
```
112+
113+
## Functional Reactive
114+
115+
functional reactive programming is a paradigm that combines functional programming with publisher and subscriber pattern. It emphasises streams of events carrying data that can be transformed along the way to the subscriber. FRP enables better handling of concurrency and asynchronous operations, making code more expressive.
116+
117+
If we’d like to showcase the above example using FRP, it would look something like this ⤵️
118+
119+
```swift
120+
var incrementSubject = PassthroughSubject<Void, Never>()
121+
var valueSubject = CurrentValueSubject<Int, Never>(0)
122+
123+
let disposableStream = Publishers.CombineLatest(incrementSubject, valueSubject)
124+
.map { _, value in value + 1 }
125+
.subscribe(valueSubject)
126+
127+
128+
print(valueSubject.value) // 0
129+
incrementSubject.send()
130+
print(valueSubject.value) // 1
131+
```
132+
133+
### Final Thoughts
134+
135+
Having a deeper understanding of FRP, beyond just describing use cases like observing keyboard input to trigger requests, can truly make you stand out in an interview. The ability to explain the differences and principles behind Combine or RxSwift will position you as a more senior candidate in the eyes of the interviewer.
136+
137+
# Quiz
138+
139+
{{< include-quiz "imperative_functional_frp.md" >}}
140+
141+
{{< footer >}}
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
{{ readFile (printf "assets/quizzes/%s" (.Get 0)) | markdownify }}

0 commit comments

Comments
 (0)