适用场合: 当一个类里的方法的语句过长时,就要采取从该方法中,再提取另外一个方法出来;
tag: 类 方法 语句过多 提取
提取时要注意的地方:
1. 要提取出来的代码,有几个变量, 在这些代码里,哪些变量是没有改变过,哪些变量改变了;
解决方法: 没改变的变量,采用传参的方式传到新提取的方法里; 改变的变量,采用返回值的形式返回;
2. 举例:
Class Test
{
public void testA()
{
int i;
String str = "a";
int Count = 0;
for (i = 0; i < 4; i++)
{
switch(i)
case 0: System.out.print(str); Count = Count + 1; break;
case 1: System.out.print(str); Count = Count + 2; break;
case 2: System.out.print(str); Count = Count + 3; break;
case 3: System.out.print(str); Count = Count + 4; break;
}
System.our.print(Count);
}
}
现在要从testA()方法里,把switch这一块提出来,做为一个新方法, switch里,str是没有改变的,而Count是经过改变了的,
具体做法:
Class Test
{
public void testA()
{
int i;
String str = "a";
int Count = 0;
for (i = 0; i < 4; i++)
{
Count = testA_Extract(int i, String str);
}
System.our.print(Count);
}
public int testA_Extract(int i, String str)
{
int Count = 0;
switch(i)
case 0: System.out.print(str); Count = Count + 1; break;
case 1: System.out.print(str); Count = Count + 2; break;
case 2: System.out.print(str); Count = Count + 3; break;
case 3: System.out.print(str); Count = Count + 4; break;
return Count;
}
}