Java Refactoring Extract Method
GitHubOfficialFirst committed by jduboisDistributed by GitHub
- Skill
- Guidelines
- Software development
- MIT
- Low risk
AutoGineer summary
Written by AutoGineer from the skill’s own files, not by the author
This skill provides a systematic approach to improving Java code quality by applying the Extract Method refactoring pattern. It guides the user through identifying complex code blocks, safely extracting them into smaller, descriptive methods, and verifying the changes through existing test suites. The process emphasizes behavior preservation, adherence to existing project styles, and safe handling of scope and visibility.
What it does
- Identifies complex methods based on length, statement count, or cyclomatic complexity.
- Provides a step-by-step procedure for extracting cohesive code blocks into new methods.
- Enforces safety rules to ensure behavior preservation and prevent functional regressions.
- Requires verification through existing test suites before and after refactoring.
- Guides the user on handling scope, visibility, and local variable management during extraction.
When to use it
- When a method exceeds 15 lines or has high cyclomatic complexity.
- When you need to improve code readability and maintainability.
- When you want to increase testability by isolating logic into smaller units.
- When you need to reduce code duplication within a class.
Advantages
- Reduces method complexity and improves overall code readability.
- Ensures refactoring is safe by mandating test verification.
- Promotes clean code practices by enforcing descriptive naming.
- Maintains existing project coding standards and Java version compatibility.
Usage examples
- “Refactor the processOrder method in my OrderService class using Extract Method.”
- The agent will analyze the method for complexity, suggest logical blocks to extract, provide the refactored code, and instruct you to run your test suite to verify the changes.
- “I have a 50-line method that handles user authentication. Can you help me break it down?”
- The agent will identify cohesive segments within the authentication logic, propose new private methods for each segment, and guide you through the safe extraction process.
Install
Download the skill as a ZIP:
https://mp-staging.autogineer.com/agent-skills/github/java-refactoring-extract-method/downloadUnzip it into the cross-client skills folder of your project:
mkdir -p .agents/skills && unzip java-refactoring-extract-method.zip -d .agents/skills
Documentation by jdubois
Refactoring Java Methods with Extract Method
Role
You are an expert in refactoring Java methods.
Below are 2 examples (with titles code before and code after refactoring) that represents Extract Method.
Code Before Refactoring 1:
public FactLineBuilder setC_BPartner_ID_IfValid(final int bpartnerId) {
assertNotBuild();
if (bpartnerId > 0) {
setC_BPartner_ID(bpartnerId);
}
return this;
}Code After Refactoring 1:
public FactLineBuilder bpartnerIdIfNotNull(final BPartnerId bpartnerId) {
if (bpartnerId != null) {
return bpartnerId(bpartnerId);
} else {
return this;
}
}
public FactLineBuilder setC_BPartner_ID_IfValid(final int bpartnerRepoId) {
return bpartnerIdIfNotNull(BPartnerId.ofRepoIdOrNull(bpartnerRepoId));
}Code Before Refactoring 2:
public DefaultExpander add(RelationshipType type, Direction direction) {
Direction existingDirection = directions.get(type.name());
final RelationshipType[] newTypes;
if (existingDirection != null) {
if (existingDirection == direction) {
return this;
}
newTypes = types;
} else {
newTypes = new RelationshipType[types.length + 1];
System.arraycopy(types, 0, newTypes, 0, types.length);
newTypes[types.length] = type;
}
Map<String, Direction> newDirections = new HashMap<String, Direction>(directions);
newDirections.put(type.name(), direction);
return new DefaultExpander(newTypes, newDirections);
}Code After Refactoring 2:
public DefaultExpander add(RelationshipType type, Direction direction) {
Direction existingDirection = directions.get(type.name());
final RelationshipType[] newTypes;
if (existingDirection != null) {
if (existingDirection == direction) {
return this;
}
newTypes = types;
} else {
newTypes = new RelationshipType[types.length + 1];
System.arraycopy(types, 0, newTypes, 0, types.length);
newTypes[types.length] = type;
}
Map<String, Direction> newDirections = new HashMap<String, Direction>(directions);
newDirections.put(type.name(), direction);
return (DefaultExpander) newExpander(newTypes, newDirections);
}
protected RelationshipExpander newExpander(RelationshipType[] types,
Map<String, Direction> directions) {
return new DefaultExpander(types, directions);
}Safety Rules
Behaviour-preserving only: no functional change, no removed logic, no changed exceptions, side-effect order or visibility of the original method.
Baseline first: run the narrowest green test command for the code (
./mvnw -q -Dtest=MyTest test,./gradlew test --tests MyTest) or./mvnw verify/./gradlew build. Re-run it after every extraction. If the baseline is red, stop and report.If the code has no tests, stop and report; propose characterization tests first. Never delete or weaken tests.
One extraction per step (one commit each when the user asks for commits) so each is reviewable and revertible.
Prefer the IDE refactoring: use an available IDE tool that exposes Extract Method (it handles parameters and return values safely). The Copilot CLI
lsptool offers navigation and rename but no code actions, so configuring jdtls throughlsp-setupdoes not provide it; otherwise extract by hand and validate with the compiler and tests.Extracted methods are
privateby default. Do not add public/protected methods, change the existing signature, or touch generated code (target/,build/generated,@Generated) without asking the user.Watch for: local variables modified in the block (return a value or introduce a small result type), multiple results, checked exceptions,
return/break/continueinside the block, andsynchronized/transaction-annotated methods (extractedprivatemethods called onthisbypass Spring proxies and AOP).
Task
Apply Extract Method to improve readability, testability, cohesion and consistency.
Identify candidate methods (rough guide: > 15 lines, > 10 statements or cyclomatic complexity > 10) and cohesive blocks inside them.
Extract each block into a descriptively named method, following the existing code style and the project's Java level (check
maven.compiler.release/ toolchain; do not use newer syntax).Add a one-line comment above each new method only if its name does not already convey its purpose.
Compile and run the tests; report the methods changed, the commands run and their results.
Output complete, compilable code for each changed method.
Code to be Refactored:
Now, assess all methods with high complexity and refactor them using Extract Method
Files
- ATTRIBUTION.mdAdded by AutoGineer893 B
- LICENSELicence file added by AutoGineer1.0 KiB
- SKILL.md4.8 KiB
Requirements and compatibility
Written for: GitHub Copilot
Works with: Claude Code, Claude apps, OpenAI Codex, GitHub Copilot, Cursor, Gemini CLI, Kiro, OpenCode, Goose, Amp, Roo Code, JetBrains Junie, Factory Droid, Devin (ex-Windsurf), Mistral Vibe, OpenHands, Letta
“Works with” means the tool reads the open Agent Skills format; a skill written for one tool may use features others lack.
Security
What our scanner noticed· Low risk
- Phrasing that asks for actions without confirmation
A static scan is not a guarantee. Skills are third-party content: review a skill before you let an agent use it.
Attribution and licence
- First committed by
jdubois
- Publisher
- GitHub (Official)
- Distributed by
- GitHub
- Source
- github/awesome-copilot · skills/java-refactoring-extract-method · commit 797337f
- Licence
- MIT License (redistribution allowed)
- LICENSE (added by AutoGineer from LICENSE)
- ATTRIBUTION.md (written by AutoGineer)
- Synced
- Contributors
- jdubois
AutoGineer is not affiliated with or endorsed by jdubois or GitHub.
Download ZIP
The ZIP holds the skill’s files, its licence files and an ATTRIBUTION.md. Download java-refactoring-extract-method.zip