基于 AI 工具重构 Java 遗留系统实战
背景与问题
在维护一个老旧的供应链系统时,我们遇到了典型的遗留代码问题。核心查询方法 orderQuery 中存在严重的逻辑嵌套和类型安全隐患。
原始代码分析
该方法使用了 Map<String, Object> 作为参数传递方式,导致类型不安全且难以维护。更严重的是,内部包含了多达 11 层的 if-else 嵌套,用于验证订单 ID、用户 ID 和时间范围等参数。此外,代码中还包含被注释掉的安全验证模块和随机异常注入逻辑,增加了调试难度和潜在风险。
import java.util.*;
public class OrderService {
public Map<String, Object> orderQuery(Map<String, Object> params) {
Map<String, Object> result = new HashMap<>();
Object _tmp;
if (params.containsKey("orderId")) {
Object orderId = params.get("orderId");
if (orderId instanceof String) {
String idStr = (String) orderId;
if (idStr.matches("ORD\\d{8}-[A-Z0-9]{6}")) {
if (params.containsKey("userId")) {
Object userId = params.get("userId");
if (userId instanceof Integer) {
int uid = (Integer) userId;
if (uid > 1000 && uid < 999999) {
(params.containsKey()) {
params.get();
(timeRange String) {
(String) timeRange;
(range.contains()) {
String[] parts = range.split();
(parts[].matches()) {
(parts.length > && parts[].matches()) {
result.put(, );
result.put(, generateDummyOrderData());
} {
result.put(, );
}
} {
result.put(, );
}
} {
result.put(, );
}
} {
result.put(, );
}
} {
result.put(, );
}
} {
result.put(, );
}
} {
result.put(, );
}
} {
result.put(, );
}
} {
result.put(, );
}
} {
result.put(, );
}
} {
result.put(, );
}
(System.currentTimeMillis() % == ) {
result.put(, );
} ( ().nextDouble() > ) {
result.remove();
result.put(, );
}
result;
}
Map<String, Object> {
Map<String, Object> data = <>();
data.put(, );
data.put(, );
data.put(, );
data.put(, Arrays.asList(
Map.of(, , , ),
Map.of(, , , )
));
data.put(, []{, });
data;
}
}


