Refactoring
Refactoring is changing the structure of code without changing what it does. Extracting repeated lines into a function, renaming x to total_grams, splitting a long function, and replacing a nested condition with an early return are all refactorings. Adding a feature and fixing a defect change observable behavior. Performance optimization has a different primary aim; it can preserve functional outputs, and a refactoring can incidentally improve performance.
Duplication is the usual trigger. The same cleaning rule pasted into three places means three places to find when the rule changes, and the copy nobody remembers keeps producing the old result. Moving it into one named function makes the rule single-sourced, and modularity follows: each function has one task, and a caller reads as a sequence of named steps rather than a wall of statements.
The condition that makes refactoring safe is a way to tell that behavior did not change: automated tests, or at minimum a set of known inputs and outputs recorded before the change and compared after. Without that, restructuring is a rewrite whose result nobody has checked. A few passing examples are evidence, not proof that every possible behavior is unchanged. Work in small steps and verify each one, so a difference points at the step that caused it.
Names carry much of the benefit. Code that states its purpose through function and variable names needs fewer comments explaining what it does, leaving comments for why a choice was made. Readability is not decoration here: shared code is read far more often than it is written, and a structure someone else can follow is what makes a change safe to attempt at all.
References: Refactoring (Martin Fowler), PEP 8: Style guide for Python code. See it in use in Python Functions, Modules, and Classes.
Discover more from Insightful Data Lab
Subscribe to get the latest posts sent to your email.
