《重构——改善既有代码》
Motivation
坚持这样一条原则:任何有返回值的函数,都不应该有看得到的副作用。所以查询和修改必须分开。
Mechanics
ü 新建一个查询函数,其返回值与原函数相同;修改原函数,令他调用查询函数,并返回查询结果。
ü 将调用原函数的代码改为调用查询函数。然后在调用查询函数的那一行之前调用原函数。
ü 修改原函数,删除return语句,将原函数返回值改为void。
Eclipse重构菜单中没有直接对应的选项,不过还是可以通过组合命令实现,decompose method + [Inline]。 其核心思想是,先将函数分解为纯粹的查询与 modify 两部分,然后利用内联,将原函数自动替换为上面两个函数。
// sendAlert是modify部分, 查询people name是query部分
String foundMiscreant(String[] people) {
for (int i = 0; i < people.length; i++) {
if (people[i].equals("Don")) {
sendAlert();
return "Don";
}
if (people[i].equals("John")) {
sendAlert();
return "John";
}
}
return "";
}
// 1. 分解上面函数为查询和modify两部分,一般可以考虑Extract Method,但往往需要根据理解,分解代码,这里我直接列出结果
// sendAlert是modify部分, 查询people name是query部分
String foundMiscreant(String[] people) {
String name = queryMiscreant(people);
if(!name.isEmpty()) sendAlert();
return name;
}
private String queryMiscreant(String[] people) {
for (int i = 0; i < people.length; i++) {
if (people[i].equals("Don")) {
return "Don";
}
if (people[i].equals("John")) {
return "John";
}
}
return "";
}
// 2 [Inline] 原函数
String foundMiscreant(String[] people) {
String name =queryMiscreant(people);
if(!name.isEmpty()) sendAlert();
return name;
}
调用原来函数的地方会自动做如下调整:
void checkSecurity(String[] people) {
String found =foundMiscreant(people);
someLaterCode(found);
}
||
V
void checkSecurity(String[]people) {
String name = queryMiscreant(people);
if(!name.isEmpty()) sendAlert();
String found = name;
someLaterCode(found);
}
over
以上源码可以here免费下载