Course contentsShow
← Software Engineering
Lesson 346 of 1,93310. RefactoringFree lesson

Extract Method

Learn to extract complex or duplicated code into well-named methods to improve readability and reduce duplication.

Extract Method

You'll learn how to pull out messy or repeated chunks of code into their own well-named methods to make your code clearer and easier to maintain.

The Core Idea

Extract Method is one of the most fundamental refactoring techniques. When you see a block of code that's hard to understand, too long, or duplicated in multiple places, you extract it into its own method with a descriptive name. Think of it like labeling a box: instead of dumping everything on your desk, you put related items in a labeled container so you know exactly what's inside without opening it.

This refactoring tackles several code smells directly: Long Method, Duplicate Code, and even helps with Large Class by breaking responsibilities into smaller pieces.

Why Extract Method Works

Improves Readability: A method named calculateTotalWithTax() tells you immediately what it does. Five lines of arithmetic scattered in your code forces readers to decode your intent.

Reduces Duplication: When the same calculation appears in three places, extract it once and call it three times. Now fixing a bug means changing one place, not hunting down every copy.

Enables Reuse: Once extracted, that method becomes available for other parts of your code that need the same logic.

The Process

  1. Identify the code fragment to extract
  2. Create a new method with a name that describes what it does, not how
  3. Move the code into the new method
  4. Replace the original code with a call to the new method

Key Takeaway: Extract Method transforms confusing or duplicated code blocks into clearly-named, reusable methods that make your program's structure obvious at a glance.