From baeafc5ccc4a9893d22e6629db97720e3fa6d3ae Mon Sep 17 00:00:00 2001 From: Pjotr Prins Date: Sun, 3 Dec 2023 09:47:38 -0600 Subject: Rename/move --- topics/programming/code-antipatterns.gmi | 93 ++++++++++++++++++++++++++++++++ 1 file changed, 93 insertions(+) create mode 100644 topics/programming/code-antipatterns.gmi (limited to 'topics/programming/code-antipatterns.gmi') diff --git a/topics/programming/code-antipatterns.gmi b/topics/programming/code-antipatterns.gmi new file mode 100644 index 0000000..2544451 --- /dev/null +++ b/topics/programming/code-antipatterns.gmi @@ -0,0 +1,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'] +``` -- cgit v1.2.3