Refactoring 007 — Extract Class
Behavior is repeated across the system. But you are missing a concept.
TL;DR: Put together what belongs together
Problems Addressed 😔
Code Duplication
Missing Abstraction
Low Cohesion
Related Code Smells 💨
Context 💬
When a class starts doing work that should be delegated to others, it suffers from Low Cohesion.
You often see this through “Data Clumps”—groups of variables that always travel together—or methods that seem unrelated to the class’s primary responsibility.
This bloat makes the code harder to understand and creates a “God Object” that changes for too many different reasons.
You need to extract these related behaviors and properties into a new, dedicated class, you give a name to a previously hidden concept.
This not only promotes code reuse across the system but also ensures that each class has a single, well-defined reason to change.
You are not just moving code; you are discovering the missing abstractions in your domain model.
Steps 👣
Extract the methods (and accidentally the properties) coupled into a new concept
Use the new concept
Sample Code 💻
Before 🚨
final class Person {
private String name;
// Below cohesive properties
private String homeAreaCode;
private String homeNumber;
public String name() {
return name;
}
// Below cohesive behavior
public String telephoneNumber() {
return ("(" + homeAreaCode + ") " + homeNumber);
}
String areaCode() {
return homeAreaCode;
}
String officeNumber() {
return officeNumber;
}
}After 👉
// 1. Extract the methods (and accidentally the properties)
// coupled into a new concept
public class TelephoneNumber {
private String number;
private String areaCode;
public String telephoneNumber() {
return ("(" + areaCode + ") " + number);
}
public String areaCode() {
return areaCode;
}
public String number() {
return number;
}
}
final class Person {
private String name;
// 2. Use the new concept
private TelephoneNumber officeTelephone = new TelephoneNumber();
public String name() {
return name;
}
public String telephoneNumber() {
return officeTelephone.getTelephoneNumber();
}
}Type 📝
[X] Automatic
Most IDEs implement this safe refactor.
Safety 🛡️
This is a safe refactoring.
Why is the Code Better? ✨
Logic code is in just one place together with its rules
Tags 🏷️
Hierarchies
Level 🔋
[X] Intermediate
Related Refactorings 🔄
See also 📚
Credits 🙏
Image from drpepperscott230 on Pixabay
This article is part of the Refactoring Series


