将属性用作局部变量是一种好习惯吗?在有许多方法使用某些变量的情况下,在每种方法中,变量值都会发生变化。这避免了多次创建新变量和代码增加。有什么建议吗?
private void method1(){
int totalLength = length1 + 10;
int totalBreath = (breath1 + breath2) + 20;
int size = (totalLength * totalLength);
System.out.println(size);
}
private void method2(){
int totalLength = length1 + 20;
int totalBreath = (breath1 + breath2) + 30;
int size = (totalLength * totalLength);
System.out.println(size);
}
private void method3(){
int totalLength = length1 + 60;
int totalBreath = (breath1 + breath2) + 10;
int size = (totalLength * totalLength);
System.out.println(size);
}
如您所见,每个方法中都会重复 totalLength、totalBreath、size。我可以将它们作为类的字段吗?所以,我不需要在每个方法中都声明它。
private void method1(){
totalLength = length1 + 10;
totalBreath = (breath1 + breath2) + 20;
size = (totalLength * totalLength);
System.out.println(size);
}