summaryrefslogtreecommitdiff
path: root/topics/programming/code-antipatterns.gmi
blob: 2544451ac1d9325ce2fca7cd61dd0e865a2c587f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
# Coding Anti-Patterns

This document contains some anti-patterns that have either been discussed during code-reviews or noticed by some one when refactoring any of GN's code-base.  Use these "ideas" as a reference, and apply reasonable judgement depending on what you are working on.


## [Python] Don't pass mutable types as arguments

Consider:

```
from typing import List


_l = ['a', 'b', 'c']


def add_pvalue(l: List, val: str) -> List:
    l.append(val)
    return l

print(f"{_l=}\n")
print(f"{add_pvalue(_l, 'd')=}\n")
print(f"{_l=}")

```

which outputs (note that _l in the global scope has changed):

```
_l=['a', 'b', 'c']

add_pvalue(_l, 'd')=['a', 'b', 'c', 'd']

_l=['a', 'b', 'c', 'd']
```

A better fix would be:


```
from typing import List


_l = ['a', 'b', 'c']


def add_pvalue(l: List, val: str) -> List:
    l = l.copy()
    l.append(val)
    return l

print(f"{_l=}\n")
print(f"{add_pvalue(_l, 'd')=}\n")
print(f"{_l=}")
```

which now does the right thing:

```
_l=['a', 'b', 'c']

add_pvalue(_l, 'd')=['a', 'b', 'c', 'd']

_l=['a', 'b', 'c']

```

Best, use immutable types:

```
from typing import Tuple


_l = ['a', 'b', 'c']


def add_pvalue(l: Tuple, val: str) -> Tuple:
    return l + (val,)

print(f"{_l=}\n")
print(f"{add_pvalue(tuple(_l), 'p')=}\n")
print(f"{_l=}")
```

which outputs:

```
_l=['a', 'b', 'c']

add_pvalue(tuple(_l), 'p')=('a', 'b', 'c', 'p')

_l=['a', 'b', 'c']
```