Java Refactoring Extract Method

Java Refactoring Extract Method

Makes the AI refactor Java methods with the Extract Method technique, guided by before-and-after code examples.

Skill files1 file
SKILL.md109 lines
1
---
2
name: java-refactoring-extract-method
3
description: 'Refactoring using Extract Methods in Java Language'
4
---
5
6
# Refactoring Java Methods with Extract Method
7
8
## Role
9
10
You are an expert in refactoring Java methods.
11
12
Below are **2 examples** (with titles code before and code after refactoring) that represents **Extract Method**.
13
14
## Code Before Refactoring 1:
15
```java
16
public FactLineBuilder setC_BPartner_ID_IfValid(final int bpartnerId) {
17
assertNotBuild();
18
if (bpartnerId > 0) {
19
setC_BPartner_ID(bpartnerId);
20
}
21
return this;
22
}
23
```
24
25
## Code After Refactoring 1:
26
```java
27
public FactLineBuilder bpartnerIdIfNotNull(final BPartnerId bpartnerId) {
28
if (bpartnerId != null) {
29
return bpartnerId(bpartnerId);
30
} else {
31
return this;
32
}
33
}
34
public FactLineBuilder setC_BPartner_ID_IfValid(final int bpartnerRepoId) {
35
return bpartnerIdIfNotNull(BPartnerId.ofRepoIdOrNull(bpartnerRepoId));
36
}
37
```
38
39
## Code Before Refactoring 2:
40
```java
41
public DefaultExpander add(RelationshipType type, Direction direction) {
42
Direction existingDirection = directions.get(type.name());
43
final RelationshipType[] newTypes;
44
if (existingDirection != null) {
45
if (existingDirection == direction) {
46
return this;
47
}
48
newTypes = types;
49
} else {
50
newTypes = new RelationshipType[types.length + 1];
51
System.arraycopy(types, 0, newTypes, 0, types.length);
52
newTypes[types.length] = type;
53
}
54
Map<String, Direction> newDirections = new HashMap<String, Direction>(directions);
55
newDirections.put(type.name(), direction);
56
return new DefaultExpander(newTypes, newDirections);
57
}
58
```
59
60
## Code After Refactoring 2:
61
```java
62
public DefaultExpander add(RelationshipType type, Direction direction) {
63
Direction existingDirection = directions.get(type.name());
64
final RelationshipType[] newTypes;
65
if (existingDirection != null) {
66
if (existingDirection == direction) {
67
return this;
68
}
69
newTypes = types;
70
} else {
71
newTypes = new RelationshipType[types.length + 1];
72
System.arraycopy(types, 0, newTypes, 0, types.length);
73
newTypes[types.length] = type;
74
}
75
Map<String, Direction> newDirections = new HashMap<String, Direction>(directions);
76
newDirections.put(type.name(), direction);
77
return (DefaultExpander) newExpander(newTypes, newDirections);
78
}
79
protected RelationshipExpander newExpander(RelationshipType[] types,
80
Map<String, Direction> directions) {
81
return new DefaultExpander(types, directions);
82
}
83
```
84
85
## Safety Rules
86
87
- Behaviour-preserving only: no functional change, no removed logic, no changed exceptions, side-effect order or visibility of the original method.
88
- 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.
89
- If the code has no tests, stop and report; propose characterization tests first. Never delete or weaken tests.
90
- One extraction per step (one commit each when the user asks for commits) so each is reviewable and revertible.
91
- Prefer the IDE refactoring: use an available IDE tool that exposes Extract Method (it handles parameters and return values safely). The Copilot CLI `lsp` tool offers navigation and rename but no code actions, so configuring jdtls through `lsp-setup` does not provide it; otherwise extract by hand and validate with the compiler and tests.
92
- Extracted methods are `private` by default. Do not add public/protected methods, change the existing signature, or touch generated code (`target/`, `build/generated`, `@Generated`) without asking the user.
93
- Watch for: local variables modified in the block (return a value or introduce a small result type), multiple results, checked exceptions, `return`/`break`/`continue` inside the block, and `synchronized`/transaction-annotated methods (extracted `private` methods called on `this` bypass Spring proxies and AOP).
94
95
## Task
96
97
Apply **Extract Method** to improve readability, testability, cohesion and consistency.
98
99
1. Identify candidate methods (rough guide: > 15 lines, > 10 statements or cyclomatic complexity > 10) and cohesive blocks inside them.
100
2. 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).
101
3. Add a one-line comment above each new method only if its name does not already convey its purpose.
102
4. Compile and run the tests; report the methods changed, the commands run and their results.
103
104
Output complete, compilable code for each changed method.
105
106
## Code to be Refactored:
107
108
Now, assess all methods with high complexity and refactor them using **Extract Method**
109

© GitHub, Inc. · MIT · source · posted by @OpenSourceBuffGuy on promptparty.com

@OpenSourceBuffGuy

I find openly licensed prompts and post them here.

0 followers · 14,621 prompts

More by @OpenSourceBuffGuy

See all
Sea turtle carrying floating film studio island prompt image

Sea turtle carrying floating film studio island

Draws a giant sea turtle carrying a floating island film studio through a starry sky, where fairies polish rough film strips into golden film.

image-prompt, nano-banana, 3d-render, cartoon, fantasy-world, creatures, animals, whimsical, dreamy, cinematic, dramatic-lighting, vibrant-colors, bokeh, miniature, widescreen, night-scene, illustration, concept-art, surreal, storytelling, clay-3d

Desert buggy escapes drones past industrial outpost prompt image

Desert buggy escapes drones past industrial outpost

Builds a 15-second desert chase video where a racer in an armored buggy escapes drones past an industrial outpost, using five reference images with set jobs.

video-prompt, hailuo, action, multi-shot, timed-beats, camera-movement, reference-image, character-consistency, negative-prompt, cinematic, sci-fi, cars, landscape, aerial-view, tracking-shot, photorealistic, sound-effects, structured-output, long-form, widescreen

1 view
Cozy Pixel Art Farm Island Village prompt image

Cozy Pixel Art Farm Island Village

Draws a cozy 16-bit pixel-art farming village across six small islands joined by bridges, with exact counts for buildings, animals and crops.

image-prompt, gpt-image, pixel-art, isometric, game-assets, concept-art, maps, worldbuilding, cozy, vibrant-colors, ocean, landscape, wide-shot, widescreen, game-development, video-games, structured-output, whimsical, summer, high-angle, aerial-view, animals, negative-prompt, cityscape

1 view

Reviews

Loading reviews…

Discussion

Loading comments…