Community코딩 & 개발github.com

extract-class

Split a class or module that has multiple responsibilities into smaller cohesive units. Use when a class has distinct clusters of fields and methods that change together, when a subset of behavior belongs to a separate concept, or when a class is hard to name because it does too much. Scans the target file, proposes extraction boundaries, and edits only after approval.

extract-class란 무엇인가요?

extract-class is a Claude Code agent skill that split a class or module that has multiple responsibilities into smaller cohesive units. Use when a class has distinct clusters of fields and methods that change together, when a subset of behavior belongs to a separate concept, or when a class is hard to name because it does too much. Scans the target file, proposes extraction boundaries, and edits only after approval.

지원 대상~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/Bouzidi-Youssef/refactor-skill/tree/HEAD/.opencode/skills/extract_class

Installed? Explore more 코딩 & 개발 skills: steipete/bluebubbles, steipete/eightctl, steipete/blucli · View all 6 →

즐겨 사용하는 AI에게 물어보기

이 에이전트 스킬이 미리 로드된 새 채팅을 엽니다.

문서

Extract Class

Category B — Moving features and responsibilities

Create a new class/module for a cohesive subset of data and behavior, then move that subset out of the original class.

Extract Class is the class-level answer to "this thing has more than one reason to change." It makes responsibilities explicit by giving each responsibility a home.


Motivation

The smell

  • Multiple responsibility clusters. One group of fields and methods deals with pay; another deals with mailing address; another deals with persistence.
  • Data clumps inside a class. Several fields are always passed around or used together and represent a concept.
  • Methods change together. A subset of methods is edited for one kind of change, while another subset changes for a different reason.
  • Hard-to-name class. The class name is vague (Manager, Handler, Record) because it owns too many concerns.
  • Large class with weak cohesion. The class has many fields, but most methods only use a subset.

Fowler's heuristic: a class should be a crisp abstraction, handle a few clear responsibilities, or be easier to understand.

The design principle

  • Single Responsibility / cohesion. A class should have one primary reason to change. Fields and methods that belong to the same concept should live together.
  • Explicit concepts. When a hidden concept gets a name and type, code becomes easier to navigate, test, and reuse.
  • Encapsulation. Moving data with the behavior that operates on it reduces feature envy and scattered rules.
  • Behavior preservation. Extraction changes structure, not observable behavior. Public behavior should remain the same unless the refactoring intentionally includes a delegated API change.

Extract Class is not:

  • splitting classes arbitrarily by line count;
  • creating a new class for every field;
  • moving data away from the behavior that needs it.

When not to extract

  • The class is already cohesive. Splitting it would create indirection without a clearer model.
  • The proposed class has no behavior and no real concept. A dumb data bag may be fine, but do not extract unless it clarifies responsibility.
  • The fields/methods are not truly cohesive. If they do not change together or represent one concept, the boundary is wrong.
  • The extraction would create tight bidirectional coupling with no clarity gain. Reconsider the boundary.
  • A simpler move is enough. Sometimes Extract Function, Move Function, or Introduce Parameter Object solves the problem.

Mechanic

Before you start

  1. Read the whole class/module and map fields to methods. Look for clusters: which methods use which fields?
  2. Identify the responsibility to extract and give it a clear name.
  3. Find existing checks. Use tests/type checker/linter/run paths that exist. Do not add tests unless asked.
  4. Decide how the old class will relate to the new one: composition/delegation is the default.

Steps

  1. Choose one cohesive cluster. Pick fields and methods that represent one concept or reason to change.
  2. Create the new class/module. Name it after the concept, not after Data, Info, or Helper unless that is truly the domain term.
  3. Move fields first. Copy/move the data into the new class. Initialize it in the old class or accept it as a dependency.
  4. Move methods next. Start with methods that use only the moved fields. Then move methods that need minor parameter/reference adjustments.
  5. Preserve the old interface when needed. Keep old methods as thin delegates if callers depend on them. Remove delegation only when safe and in scope.
  6. Update callers gradually. Prefer small steps: construct/own the new class, delegate, then switch callers.
  7. Run checks after each step. Especially after moving state and updating construction.
  8. Clean up. Remove unused fields/methods from the old class, simplify constructor parameters if appropriate, and ensure dependencies point in a sensible direction.

Deciding what moves

SignalAction
Field is used only by moved methodsMove it to the new class.
Field is shared by both responsibilitiesKeep it where it fits best; pass it as parameter or expose a narrow accessor.
Method uses mostly moved fieldsMove the method.
Method mixes responsibilitiesExtract Function first, then move the extracted part.
Old callers need the old methodKeep a delegating wrapper temporarily.
New class needs owner dataPass required data in; avoid back-references unless necessary.

Rules that keep the move safe:

  • Move one cohesive cluster at a time.
  • Preserve observable behavior and public contracts unless explicitly changing them.
  • Prefer composition over inheritance for the extracted responsibility.
  • Avoid bidirectional dependencies; if unavoidable, keep them narrow and intentional.
  • Do not mix extraction with feature changes.

Example

Before

class Employee:
    def __init__(self, name, base_salary, bonus_rate, street, city, postal_code):
        self.name = name
        self.base_salary = base_salary
        self.bonus_rate = bonus_rate
        self.street = street
        self.city = city
        self.postal_code = postal_code

    def annual_pay(self):
        return self.base_salary + self.base_salary * self.bonus_rate

    def mailing_label(self):
        return f"{self.name}\n{self.street}\n{self.postal_code} {self.city}"

The class mixes compensation and mailing concerns.

After

class MailingAddress:
    def __init__(self, street, city, postal_code):
        self.street = street
        self.city = city
        self.postal_code = postal_code

    def label(self, name):
        return f"{name}\n{self.street}\n{self.postal_code} {self.city}"


class Employee:
    def __init__(self, name, base_salary, bonus_rate, address):
        self.name = name
        self.base_salary = base_salary
        self.bonus_rate = bonus_rate
        self.address = address

    def annual_pay(self):
        return self.base_salary + self.base_salary * self.bonus_rate

    def mailing_label(self):
        return self.address.label(self.name)

Employee keeps compensation responsibility; MailingAddress owns address formatting. Behavior is preserved through delegation.

A non-example

Do not extract BaseSalaryCalculator if it only wraps one trivial multiplication and has no real concept. That adds indirection without clarifying the model.


Related refactorings

  • Move Function / Move Field — the mechanical moves used during extraction.
  • Extract Function — separate mixed responsibilities inside a method before moving them.
  • Introduce Parameter Object — useful when a data clump should become a value object rather than a service-like class.
  • Inline Class — the inverse, when an extracted class stops earning its keep.

Running this skill on a file

When invoked with @extract_class:

  1. Confirm the target. Use the file/class named by the user. If none is named, ask for one. Read it completely.
  2. Map responsibilities. Report field clusters, method clusters, and the proposed new class/module name.
  3. Inventory candidates. For each candidate, report:
    • fields and methods to move,
    • why they form a cohesive responsibility,
    • dependencies that stay behind,
    • risk: low (clear cluster, private/internal), medium (shared fields or many callers), high (public API, serialization/persistence, inheritance).
  4. Propose before editing. Present the extraction boundary and migration plan. Do not change files on the first pass.
  5. Apply one extraction at a time. Move fields, then methods, then update callers/delegates. Keep diffs small.
  6. Run existing checks after each step. If no checks exist, state what was not verified.
  7. Report. Say what moved, what delegated, what stayed, and any follow-up refactorings.
  8. Stop and ask if the boundary is unclear, if shared state creates tight coupling, or if public behavior would change.

Checklist

  • The new class/module has a clear, cohesive responsibility.
  • Moved fields and methods belong together.
  • Public behavior is preserved or intentionally delegated.
  • Bidirectional dependencies are avoided or explicitly justified.
  • Checks pass, or the unverified risk is stated.

Individual skills in this repo

This repo contains 4 individual skills — each has its own dedicated page.

extract-function

Turn a coherent block of code into a well-named function without changing behavior. Use when a block needs a comment to be understood, a function is long or mixes levels of abstraction, logic is duplicated, or a loop or conditional arm does several jobs. Scans the target file, proposes candidates and names, and edits only after approval.

inline-function

Replace a function call with the function's body when the indirection adds no meaning. Use when a function body is as clear as its name, a wrapper only delegates, a helper is used once and forces unnecessary navigation, or bad factoring should be undone by inlining before re-extracting. Scans the target file, proposes candidates, and edits only after approval.

refactoring-router

Entry-point refactoring and rewrite skill. Use when the user wants to refactor, clean up, improve, simplify, or rewrite a codebase/file/module and needs smell-driven analysis, technique selection, or a new implementation approach. Detects refactor vs rewrite intent, asks type/mode/risk/scope/depth or ambition, then dispatches specialized subagents in an automatic loop. Triggers: "refactor this", "rewrite this", "clean this up", "improve this codebase", "reimplement this".

remove-dead-code

Delete code that is never executed, never referenced, or no longer reachable. Use when you find unused functions, variables, imports, parameters, branches, or files; when obsolete compatibility paths are no longer needed; or when dead code obscures behavior. Scans the target file, proposes safe deletions, and edits only after approval.

관련 스킬