Module 6 · Writing Clean Code
On this page 10 headings
Learning goals: Spot maintainability problems and refactor without changing the observable behaviour of a program.
What Is a Code Smell?
A code smell is a warning sign that code may be difficult to understand, change or maintain. The program might still run and produce the expected output. Examples include repeated code, overly long functions and confusing comments. The lecture uses ideas from Robert C. Martin's Clean Code.
Remember: A smell suggests closer inspection; it is not necessarily a runtime failure.
Redundant Comments
Use comments only to explain why; i++ // increment i by 1 is redundant.
Remember: Explain intent and reasons, not an obvious operation.
Delete Commented-Out Code, Keep Git History
Delete commented-out code, because version control keeps the history.
Remember: Delete dead commented-out code; keep useful reasoning comments and Git history.
Functions Should Do One Thing
Functions should do one thing and be short.
Remember: Prefer small, cohesive functions with clear names.
Too Many Arguments and Flag Arguments
Ideally a function has zero arguments, or one, two, at most three. More than three suggests doing more than one thing, so divide it into multiple functions. Flag arguments are control coupling (seen in an earlier week); split into one function per flag value.
Remember: Think about simpler arguments and functions that communicate their purpose.
Dead Functions
Dead functions are not called anywhere, so remove them.
Remember: Remove dead functions.
DRY: Do Not Repeat Yourself
DRY: clumps of identical code → put them in simple methods and call them. A second example: many sub-conditions in one condition → put the values in a list and check membership.
Remember: One shared source of logic is easier to change consistently.
Boundary Cases and Explanatory Names
Boundaries: check behaviour at the boundary conditions. Explanatory variables: rename m to thirty_day_months.
Remember: Test edge cases and choose names that communicate meaning.
Refactoring: Improve Structure, Keep Behavior
Refactoring changes the code to improve its structure without changing its behaviour. Tools include Pylint, flake8 and vulture. Pylint is a static code analyzer: install with pip install pylint and run pylint <file>. Its messages are about naming conventions and structure, not program logic: missing docstring; names not in snake_case; C = convention, W = warning. It flags unused variables and unreachable code. VS Code and most IDEs have linters pre-installed.
Remember: Better structure, same behavior: test before and after refactoring.
Quick revision and self-check
Question: Does a code smell always mean the program fails?
Answer: No. The program may run correctly but be hard to maintain.
Question: What does DRY encourage?
Answer: Put identical clumps of code into simple methods and call them.
Question: What must remain unchanged in a refactor?
Answer: Its behaviour.
