🚀 快速安装

复制以下命令并运行,立即安装此 Skill:

npx @anthropic-ai/skills install github/awesome-copilot/java-refactoring-extract-method

💡 提示:需要 Node.js 和 NPM

使用提取方法重构 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)。

在内部执行中间步骤:

  • 首先,分析每个方法,识别那些超出阈值的方法:
    • 代码行数 > 15
    • 语句数 > 10
    • 圈复杂度 > 10
  • 对于每个符合条件的方法,识别可以提取到单独方法中的代码块。
  • 至少提取一个具有描述性名称的新方法。
  • 仅将重构后的代码输出到单个 java 代码块中。
  • 不要移除原始方法中的任何功能。
  • 在每个新方法上方添加一行注释来描述其目的。

待重构的代码:

现在,评估所有复杂度高的方法,并使用提取方法进行重构。

📄 原始文档

完整文档(英文):

https://skills.sh/github/awesome-copilot/java-refactoring-extract-method

💡 提示:点击上方链接查看 skills.sh 原始英文文档,方便对照翻译。

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。