01 / 21

Refactoring
in Java

Learn how to reduce duplication and improve clarity by restructuring existing code without changing its external behavior.

Java

What is Refactoring?

Refactoring is the process of restructuring existing code to improve its internal design while preserving its external behavior. The program does exactly the same thing before and after: you change how it is written, not what it does.

Why Refactor?

Readability
Clear code is easier for you and teammates to understand months later.
Maintainability
Fixing bugs and adding features becomes faster when code is well-organized.
Reduced Duplication
One source of truth means a fix in one place applies everywhere.

Recognizing Code Smells

A code smell is a surface-level indicator that something in your code may need refactoring. It is not a bug: the code runs fine. It is a hint that the design could be simpler or cleaner.

1
Duplicated Code: The same logic appears in multiple places.
2
Long Methods: A method tries to do too many things at once.
3
Magic Numbers: Unexplained literal values scattered in code.
4
Poor Naming: Variables or methods named x, temp, or doStuff.

The Golden Rule of Refactoring

Before Input → Output A Input → Output B messy internals Refactor After Input → Output A Input → Output B clean internals Same behavior, better structure

The DRY Principle

DRY stands for "Don't Repeat Yourself." Every piece of knowledge or logic should have a single, unambiguous representation in your codebase.

WET (Duplicated) calcTax() in Order calcTax() in Invoice calcTax() in Receipt 3 copies of same logic Bug fix needed in 3 places DRY (Single Source) TaxCalculator Order Invoice Receipt 1 source of truth Bug fix needed in 1 place

Refactoring vs. Rewriting

Refactoring Rewriting
Goal Improve structure Replace functionality
Behavior Preserved May change
Scope Small, incremental steps Large-scale overhaul
Risk Low High
Testing Tests should still pass Tests may need rewriting

Core Techniques

Extract Method
Pull repeated or complex code into its own named method.
Rename
Give variables, methods, and classes descriptive, intention-revealing names.
Extract Constant
Replace magic numbers with named constants that explain their meaning.
Simplify Conditionals
Break complex boolean expressions into well-named helper methods.

How to Apply Refactoring

1
Make sure tests pass. Before you touch anything, verify the code works correctly with existing tests.
2
Identify the smell. Find duplicated logic, a method that is too long, or a confusing name.
3
Apply one technique. Make a single, small change: extract a method, rename a variable, or introduce a constant.
4
Run tests again. Confirm the behavior has not changed.
5
Repeat. Continue with the next smell until the code is clean and clear.

Example: Extract Method

✕ Before
public void printReport() { System.out.println("=== Report ==="); double total = 0; for (Item item : items) { total += item.getPrice() * item.getQty(); } double tax = total * 0.08; System.out.println( "Total: " + (total + tax)); }
✓ After
public void printReport() { printHeader(); double total = calcSubtotal(); double tax = calcTax(total); printTotal(total + tax); } private double calcSubtotal() { double sum = 0; for (Item i : items) sum += i.getPrice() * i.getQty(); return sum; }

Example: Rename + Extract Constant

✕ Before
public boolean check(int x) { if (x >= 18 && x <= 65) { return true; } return false; }
✓ After
private static final int MIN_AGE = 18; private static final int MAX_AGE = 65; public boolean isEligible( int age) { return age >= MIN_AGE && age <= MAX_AGE; }

Example: Eliminating Duplication

✕ Before
public void greetStudent(String n) { System.out.println( "Hello, " + n + "!"); System.out.println( "Welcome to class."); } public void greetTeacher(String n) { System.out.println( "Hello, " + n + "!"); System.out.println( "Welcome to class."); }
✓ After
public void greet(String name) { System.out.println( "Hello, " + name + "!"); System.out.println( "Welcome to class."); } // Callers: greet("Alice"); // student greet("Mr. B"); // teacher

Example: Simplify Conditionals

✕ Before
if (user.getAge() >= 18 && user.hasLicense() && !user.isBanned() && car.isAvailable()) { rentCar(user, car); }
✓ After
if (canRent(user, car)) { rentCar(user, car); } private boolean canRent( User u, Car c) { return u.getAge() >= MIN_AGE && u.hasLicense() && !u.isBanned() && c.isAvailable(); }

The Refactoring Cycle

1. Run Tests All pass ✓ 2. Find Smell Duplication? Long? 3. Refactor One small step 4. Run Tests Still pass? ✓ 5. More Smells? Yes → go to step 2 Done ✓ No →

Common Mistakes

✕ Refactoring Without Tests
If you have no tests, you cannot verify behavior is preserved. Always write or run tests first.
✕ Changing Too Much at Once
Big refactors introduce risk. Make one small change, test, then make the next change.
✕ Over-Abstracting
Extracting a method used only once can make code harder to follow. Refactor when there is a real benefit.

Refactoring Techniques Summary

Technique When to Use Result
Extract Method Long methods, repeated code blocks Shorter, reusable methods
Rename Unclear variable or method names Self-documenting code
Extract Constant Magic numbers in code Named, meaningful values
Simplify Conditional Complex boolean logic Readable conditions
Remove Duplication Copy-pasted logic Single source of truth

Question 1 of 5

What is the primary goal of refactoring?

Question 2 of 5

Which refactoring techniques did the student apply?

Question 3 of 5

What should you always do before starting to refactor code?

Question 4 of 5

Which code smell was addressed by this refactoring?

Question 5 of 5

What principle does this refactoring best demonstrate?