Naming and Separating Concerns
Unit ID: M05-U08 Estimated active time: 25-35 minutes
A long cell can hide several jobs
Suppose one cell:
- reads raw values;
- cleans text;
- calculates totals;
- prints a report; and
- changes a source dictionary.
These concerns have different reasons to change.
Separate the pipeline
def clean_course_name(raw_name: str) -> str:
"""Return a display course name from supplied raw text."""
return raw_name.strip().title().replace("Ai", "AI")
def clean_status(raw_status: str) -> str:
"""Return trimmed lowercase status text."""
return raw_status.strip().lower()
def format_course_summary(name: str, hours: int, status: str) -> str:
"""Return a one-line course summary."""
return f"{name} | {hours} hours | {status}"
The orchestration remains visible:
name = clean_course_name(raw_record["name"])
status = clean_status(raw_record["status"])
summary = format_course_summary(name, raw_record["hours"], status)
print(summary)
Name by responsibility
Prefer verbs for functions that do work:
clean_statuscalculate_total_hoursformat_course_summaryvalidate_record
Avoid vague names such as process_data, do_thing, or handle when a more precise verb exists.
Keep orchestration simple
An orchestration block coordinates functions. It should read like the task sequence. If it contains detailed cleaning rules, those rules may belong in a named function.
Do not hide every line behind functions. Keep the overall flow visible to the learner.
Verify behaviour before and after refactoring
Record the expected cleaned values and summary before changing the structure. After refactoring, compare outputs. Refactoring should change organisation without changing intended behaviour.
Practice
Take repeated code that strips three status values and prints three labels. Write one clean_status() function and one format_status_label() function. Compare all outputs with the original version.
Takeaway
Separate cleaning, calculation, formatting, and orchestration. Use function names that state responsibility and verify that refactoring preserves behaviour. You are now ready for the complete checkpoint.
