Refactoring rewrites existing, working code to improve its structure or clarity while preserving what it does. Start with the code and a specific goal: make it shorter, move processing into functions, or reorganize modules. Adding a new feature can happen alongside a refactor, but it changes the program’s behavior and should be identified separately. section 8.13.1 section 9.9.1 section 18.6
A practical refactoring pass:
- Identify what must keep working. For a file counter, check its line, word, and character counts before and after the rewrite. section 8.13 section 8.13.2
- Choose a focused improvement. Shorter expressions may replace counting loops; functions can separate cleaning, counting, and reporting. Give functions clear names and return values rather than relying on globals. section 8.13.2 section 9.9 section 9.9.2
- Check the trade-off. Reading a whole file can shorten the code, but line-by-line processing handles much larger files. section 8.13.2
- Run the result, including AI-generated rewrites. A missing import can fail immediately; assigning a function’s name to its string result can fail on the next loop iteration. section 9.9.2
""" Reads a file and returns the number of lines, words,
and characters - similar to the UNIX wc utility
"""
with open('word_count.tst') as infile:
lines = infile.readlines() #1
line_count = len(lines)
word_count = sum(len(line.split()) for line in lines) #2
char_count = sum(len(line) for line in lines) #3
print(f"{line_count} lines, {word_count} words, {char_count} characters")
This shorter word counter replaces explicit count increments with len(), sum(), and generator expressions. Its readlines() call holds the file’s lines in memory. section 8.13.2
Keep a feature change distinct
Changing a word counter to accept only alphabetic words is not merely a shorter way to count the same words: it changes which inputs count. A suggested filter uses word.isalpha(). Likewise, adding wc-style -l, -w, -c, and -L options extends a counter while its existing counting logic is being reworked. Compare the resulting command with the system’s wc where available. section 8.13.1 section 8.13.2 section 11.5
Refactoring can also change a program’s organization: move text cleaning and word-frequency processing into separate functions, then separate modules in a package. Other exercises add exception handling or replace os and shutil with pathlib. Specify which behavior should remain, and review any requested additions on their own terms. Avoid changing working code solely to add type hints unless there is a good reason. section 9.9 section 18.6 section 14.4 section 12.6.1





















