Refactoring (notes)
last update: 2021-08-14
Make it work, make it right, make it fast
– Kent Beck (attributed)
Test, Change, Test again
The Zen of Python, by Tim Peters:
import this
Write code that's
- easy to read
- easy to modify
- regular
- short
- fast
Think of every line of code as a message for someone in the future.
– Linda Rising
When you look at source code, the meaning of the program should be apparent. [...] If your code needs comments, consider refactoring it so it doesn’t.
– Peter Sommerlad
Style
- Set of techniques for programming leading to a consistent use of language features
- Sometimes used in a very restricted sense to refer just to low-level rules for naming and appearance of code (coding standard)
Coding Standard
- A set of rules for what code should look like
- Common aims are to improve reliability, portability, maintainability, testability, reusability, extensibility and readability
All coding standards are disliked by programmers, even the good ones.
– Bjarne Stroutrup
- To avoid code that is poorly written (using programming language facilities in unnecessarily error-prone ways or expressing ideas in ways that obscure their meaning)
- Coding standards are trying to address incidental complexities rather than inherent complexities; sources for these are
- overly clever programmers
- undereducated programmers (not using the most appropriate language and library features)
- unnecessary variations in programming style
- inappropriate programming language
- A coding standard should
- help a programmer write good code
- by giving answers to lots of little questions
- not be annoying/ pointless/ solely a list of don'ts
- be designed for a specific application domain and a specific group of programmers
- be prescriptive as well as restrictive
Examples for real-world coding standards:
Use tools to facilitate processes, but don't let the tools become ends in themselves.
Tools
- pep8
- A tool to check your Python code against some of the style conventions in PEP 8.
- pyflakes
- simple Python source checker
- pylint
- python code static checker
- ...
- cppcheck
- Tool for static C/C++ code analysis (in repositories)
- cpplint.py
- Lint for Google's C++ coding style
- ...
Examples
- refactor old homework or the term project (speed, elegance, ...)
- open files with explicit encoding