@@ -431,3 +431,95 @@ message.send()
431431```
432432
433433** [ ⬆ back to top] ( #table-of-contents ) **
434+
435+ ### Functions should only be one level of abstraction
436+
437+ When you have more than one level of abstraction, your function is usually doing too
438+ much. Splitting up functions leads to reusability and easier testing.
439+
440+ ** Bad:**
441+
442+ ``` python
443+ def parse_better_js_alternative (code : str ) -> None :
444+ regexes = [
445+ # ...
446+ ]
447+
448+ statements = regexes.split()
449+ tokens = []
450+ for regex in regexes:
451+ for statement in statements:
452+ # ...
453+
454+ ast = []
455+ for token in tokens:
456+ # Lex.
457+
458+ for node in ast:
459+ # Parse.
460+ ```
461+
462+ ** Good:**
463+
464+ ``` python
465+ def parse_better_js_alternative (code : str ) -> None :
466+ tokens = tokenize(code)
467+ syntax_tree = parse(tokens)
468+
469+ for node in syntax_tree:
470+ # Parse.
471+
472+
473+ def tokenize (code : str ) -> list :
474+ REGEXES = [
475+ # ...
476+ ]
477+
478+ statements = code.split()
479+ tokens = []
480+ for regex in REGEXES :
481+ for statement in statements:
482+ # Append the statement to tokens.
483+
484+ return tokens
485+
486+
487+ def parse (tokens : list ) -> list :
488+ syntax_tree = []
489+ for token in tokens:
490+ # Append the parsed token to the syntax tree.
491+
492+ return syntax_tree
493+ ```
494+
495+ ** [ ⬆ back to top] ( #table-of-contents ) **
496+
497+ ### Don't use flags as function parameters
498+
499+ Flags tell your user that this function does more than one thing. Functions should do one thing. Split your functions if they are following different code paths based on a boolean.
500+
501+ ** Bad:**
502+
503+ ``` python
504+ from pathlib import Path
505+
506+ def create_file (name : str , temp : bool ) -> None :
507+ if temp:
508+ Path(' ./temp/' + name).touch()
509+ else :
510+ Path(name).touch()
511+ ```
512+
513+ ** Good:**
514+
515+ ``` python
516+ from pathlib import Path
517+
518+ def create_file (name : str ) -> None :
519+ Path(name).touch()
520+
521+ def create_temp_file (name : str ) -> None :
522+ Path(' ./temp/' + name).touch()
523+ ```
524+
525+ ** [ ⬆ back to top] ( #table-of-contents ) **
0 commit comments