Skip to content

Commit c7f2d0d

Browse files
committed
idempotence, imperative vs declarative code
1 parent f0d8b94 commit c7f2d0d

File tree

4 files changed

+44
-2
lines changed

4 files changed

+44
-2
lines changed

.vscode/settings.json

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
{
22
"cSpell.ignoreWords": [
33
"delonghi",
4+
"idempotence",
45
"iphone",
56
"nespresso"
67
]

Assets/ImperativeDeclarative.png

660 KB
Loading

Assets/PerfectFunction.png

1.16 MB
Loading

FunctionalProgramming.md

Lines changed: 43 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -37,8 +37,49 @@ const array3 = multiplyByTwo(array);
3737
console.log(array, array2, array3) // ->  [1, 2, 3] , [1, 2] , [2, 4, 6]
3838
```
3939

40-
#### <i>Example:</i> Amazon shopping feature
40+
---
41+
<br>
42+
43+
![Perfect Function](./Assets/PerfectFunction.png)
44+
45+
#### The perfect function should:
46+
47+
- Do one task and one task only
48+
- Have a return statement. If we give it an input we expect an output
49+
- Be pure (see above rules)
50+
- Have no shared state with other functions
51+
- Have immutable state. Never modify global state, always return a new copy of an input
52+
- Be composable
53+
- Be predictable
54+
55+
---
56+
<br>
57+
58+
## Idempotence
59+
60+
The idea of Idempotence is a function that always returns or does what we expect it to do.
61+
62+
<i>Example:</i>
4163

4264
```javascript
65+
function notGood(num) {
66+
console.log(num)
67+
}
68+
69+
notGood(5) // -> 5
70+
```
71+
72+
This function is idempotent because it returns the same result when called multiple times. It is not pure however as it interacts with the global scope. Practical examples of idempotent functions can be HTTP requests to an API such as deleting a user. Idempotence is useful because it helps keep code predictable.
73+
74+
---
75+
<br>
76+
77+
## Imperative Vs. Declarative
78+
79+
<b>Imperative</b> code is code that tells the machine what to do and how to do it. <b>Declarative</b> code tells it what to do and what should happen.
80+
81+
A useful analogy to think of is that computers are better at being imperative and humans are better at being declarative.
82+
83+
![Imperative Vs. Declarative](./Assets/ImperativeDeclarative.png)
4384

44-
```
85+
Machine code is very imperative. When we declare a variable the computer receives a lot of specific instructions on where to put it in which memory space, when to modify it and so on. Its very descriptive of how to do things. In contrast, as we go higher up the chain to a higher level language, it becomes more declarative. Instead of giving specific instructions of where to store it in memory etc, we just declare the variable with some sort of data and tell it what we need to get done but not how to do it. The computer takes care of that for us.

0 commit comments

Comments
 (0)