Skip to content
Computer Science · 12th Grade · Object-Oriented Design and Data Structures · Weeks 10-18

Refactoring and Code Quality

Students learn techniques for improving existing code's design without changing its external behavior, focusing on readability and maintainability.

Common Core State StandardsCSTA: 3B-AP-15CSTA: 3B-AP-21

About This Topic

Refactoring is the practice of restructuring existing code to improve its internal design while keeping its external behavior identical. In US 12th-grade CS, students learn that working software is not the same as well-designed software. Code that solves the problem but is difficult to read, duplicated across many files, or structured around how it was originally written rather than what it actually does accumulates technical debt, hidden future costs that slow every subsequent change.

Code smells are the signals that refactoring is needed: duplicated logic, functions that do five different things, variable names that describe nothing, deeply nested conditionals, and classes that have grown to hundreds of lines. Students learn to recognize these patterns and apply named refactoring techniques, such as extracting a method, renaming a variable, replacing a conditional with polymorphism, or decomposing a large class, without modifying the program's observable behavior. Automated tests are the safety net that makes refactoring safe.

Active learning methods are highly effective here because students can critique real code examples collaboratively, reach different conclusions, and defend their refactoring choices, which surfaces the judgment involved in the practice far more than any worked example can.

Key Questions

  1. Justify the importance of refactoring in the long-term maintainability of software.
  2. Identify common 'code smells' that indicate a need for refactoring.
  3. Critique a given code snippet and propose refactoring strategies to improve its quality.

Learning Objectives

  • Analyze a given code snippet for common code smells, such as duplication, long methods, or large classes.
  • Evaluate the impact of specific refactoring techniques on code readability and maintainability.
  • Propose and justify at least two refactoring strategies for a provided code example, explaining how they improve quality without altering functionality.
  • Compare the 'before' and 'after' versions of refactored code, articulating the specific design improvements made.

Before You Start

Functions and Methods

Why: Students need a solid understanding of how functions and methods work to apply techniques like 'Extract Method'.

Control Flow (Conditionals and Loops)

Why: Recognizing complex or deeply nested control flow is a key indicator of code smells that refactoring can address.

Basic Object-Oriented Principles (if applicable)

Why: Understanding concepts like classes and objects is foundational for refactoring techniques specific to object-oriented code, such as 'Decompose Conditional' or 'Replace Conditional with Polymorphism'.

Key Vocabulary

RefactoringThe process of restructuring existing computer code without changing its external behavior. It aims to improve non-functional attributes of the software.
Code SmellA surface indication in the code that usually corresponds to a deeper problem in the system. Examples include duplicated code or long methods.
Technical DebtThe implied cost of additional rework caused by choosing an easy (limited) solution now instead of using a better approach that would take longer. Refactoring helps pay down this debt.
Extract MethodA refactoring technique where a fragment of code within a larger method is extracted into its own new method. This improves readability and reduces duplication.
Test SuiteA collection of test cases designed to be used to test a software program. A robust test suite acts as a safety net during refactoring, ensuring behavior remains unchanged.

Watch Out for These Misconceptions

Common MisconceptionRefactoring means rewriting code from scratch when it gets too messy.

What to Teach Instead

Refactoring means making small, targeted, behavior-preserving changes, one at a time, supported by automated tests. A complete rewrite is high-risk because it abandons the tested behavior of the original. The refactoring lab, where students run tests after every small change, builds this disciplined habit effectively.

Common MisconceptionIf the code works and passes all tests, there is no reason to refactor it.

What to Teach Instead

Code that works but is hard to read causes future bugs when the next developer (often the original author six months later) misunderstands what it does. Maintainability is a form of correctness over time. Having students try to add a feature to poorly structured code before and after refactoring makes this cost visceral.

Common MisconceptionCode smells are just a matter of personal style preference.

What to Teach Instead

While some style choices are subjective, most code smells have measurable effects on how long it takes to understand and change code. Duplicated logic, for example, means a bug fix must be applied in multiple places or it will recur. Code smell identification galleries help students see the patterns that research and industry experience have identified as genuinely costly.

Active Learning Ideas

See all activities

Code Critique: Smell Identification Gallery Walk

Print five code snippets on large paper and post them around the room. Each snippet has two or three distinct code smells (long method, magic numbers, duplicate logic, poor naming, deep nesting). Groups rotate every five minutes, identify the smells with sticky notes, and propose a refactoring. The debrief compares group choices and discusses cases where multiple refactorings are defensible.

30 min·Small Groups

Pair Refactoring Lab: Before and After

Provide a working but poorly structured 80-line function. Pairs write tests first to confirm the current behavior, then refactor the code by applying at least three named techniques. They run tests after each change to confirm nothing broke. Pairs present their refactored version and explain each decision.

50 min·Pairs

Think-Pair-Share: Is This Refactoring Worth It?

Present a scenario where refactoring a module would take two days but the feature request is due in one day. Pairs argue for or against proceeding with refactoring. Share-out surfaces the real trade-offs between short-term velocity and long-term maintainability, which is a judgment engineers make constantly in industry.

15 min·Pairs

Jigsaw: Refactoring Technique Cards

Assign each small group one refactoring technique, extract method, rename variable, replace magic number with constant, replace conditional with polymorphism. Groups study their technique, create a one-page visual explanation with a before/after example, then teach it to a mixed group. The class ends with a shared reference sheet.

35 min·Small Groups

Real-World Connections

  • Software engineers at Google regularly refactor large codebases, like the Android operating system or search algorithms, to onboard new developers faster and reduce the likelihood of introducing bugs during feature development.
  • Game developers for studios like Blizzard Entertainment use refactoring to optimize performance-critical code in games such as World of Warcraft. This ensures smoother gameplay and allows for easier integration of new content and patches.
  • Financial technology companies, such as Stripe, rely on well-maintained code for their payment processing systems. Refactoring ensures the security and reliability of transactions, which is critical for customer trust and regulatory compliance.

Assessment Ideas

Quick Check

Present students with a short code snippet containing 2-3 common code smells. Ask them to identify each smell by name and briefly explain why it is problematic. For example: 'Identify the code smell in lines 5-10 and explain why it needs refactoring.'

Peer Assessment

Provide students with a small, poorly written function. Have them work in pairs to refactor it, then swap their refactored code with another pair. Each pair reviews the other's refactored code, answering: 'Did the refactoring improve readability? Did it introduce any new issues? Provide one specific suggestion for further improvement.'

Discussion Prompt

Pose the question: 'Imagine you are a junior developer joining a project with significant technical debt. How would you advocate for the importance of refactoring to your team lead, and what initial steps would you propose to start improving code quality?'

Frequently Asked Questions

What is refactoring in computer science and why does it matter?
Refactoring is the process of restructuring existing code to improve its design, making it more readable, reducing duplication, and clarifying intent, without changing what the code does. It matters because code is read far more often than it is written. Well-structured code is faster to extend, easier to debug, and less likely to introduce new bugs during changes.
What are common code smells that signal a need for refactoring?
Common code smells include: long methods that do too many things, duplicated logic in multiple places, unclear variable or function names, magic numbers without explanation, deeply nested conditionals, and classes with too many responsibilities. Each smell is a hint that the structure of the code no longer reflects the problem it solves clearly.
How do you refactor safely without breaking working code?
The key is writing automated tests before refactoring, then making small incremental changes and running tests after each one. If a test fails, you know exactly which small change broke something. This test-first safety net is what separates disciplined refactoring from risky rewrites. Version control also lets you revert any change that turns out to be wrong.
How does active learning help students develop refactoring judgment?
Refactoring involves genuine judgment: which smell to fix first, whether a particular change is worth the risk, what a method should be named to communicate intent clearly. Collaborative code critique activities, where groups analyze the same snippet and defend different refactoring choices, develop this judgment through practice and disagreement in ways that a teacher demonstrating a worked example cannot replicate.