SKILL.md
readonlyread-only
name
java-refactoring-extract-method
description
使用 Java 語言中的提取方法進行重構
使用提取方法重構 Java 方法
角色
您是重構 Java 方法的專家。
以下是 2 個範例(標題分別為重構前後的程式碼),代表提取方法。
重構前程式碼 1:
public FactLineBuilder setC_BPartner_ID_IfValid(final int bpartnerId) {
assertNotBuild();
if (bpartnerId > 0) {
setC_BPartner_ID(bpartnerId);
}
return this;
}
重構後程式碼 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));
}
重構前程式碼 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);
}
重構後程式碼 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);
}
任務
應用提取方法來改善可讀性、可測試性、可維護性、可重用性、模組化、內聚力、低耦合度與一致性。
始終回傳完整且可編譯的方法(Java 17)。
內部執行中間步驟:
- 首先,分析每個方法,找出超過門檻值的方法:
- LOC(程式碼行數)> 15
- NOM(陳述式數量)> 10
- CC(循環複雜度)> 10
- 對於每個符合條件的方法,識別可提取為獨立方法的程式碼區塊。
- 至少提取一個新方法,並使用描述性名稱。
- 僅在單一
java區塊內輸出重構後的程式碼。 - 不要移除原始方法中的任何功能。
- 在每個新方法上方加入一行註解,說明其用途。
待重構的程式碼:
現在,評估所有高複雜度的方法,並使用提取方法進行重構






