diff options
author | Munyoki Kilyungi | 2022-09-29 12:15:20 +0300 |
---|---|---|
committer | Munyoki Kilyungi | 2022-09-29 12:15:49 +0300 |
commit | 3763b97e1271802a3137b5b116eb67e255de61ca (patch) | |
tree | 0e9062daac5882ecffc476467bcf2c268b189e36 /topics | |
parent | 2c0c65a38c66b3eb1bb2e409c57b1e536f2181e8 (diff) | |
download | gn-gemtext-3763b97e1271802a3137b5b116eb67e255de61ca.tar.gz |
Note coding anti-patterns observed in GN code
* topics/code-antipatterns: New file.
Diffstat (limited to 'topics')
-rw-r--r-- | topics/code-antipatterns.gmi | 93 |
1 files changed, 93 insertions, 0 deletions
diff --git a/topics/code-antipatterns.gmi b/topics/code-antipatterns.gmi new file mode 100644 index 0000000..248effe --- /dev/null +++ b/topics/code-antipatterns.gmi @@ -0,0 +1,93 @@ +# Introduction + +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'] +``` |