3

我在 Java 中有一个微不足道但令人恼火的问题。假设我们有以下类和方法:

class A{
    void doSth(int[] array){    
        int index1, index2, index3;
        int value1, value2, value3;    

        if(array[index1] > 10){    
            //Long code modifies value1, value2, value3
        }  

        if(array[index3] > 100){    
            //Same long code modifies value1, value2, value3
        }      

        if(array[index2] > 20){    
            //Same long code modifies value1, value2, value3
        }    
    }

不管这是试图实现什么,我想以某种方式使这种冗余消失。通常,我会将值传递给 hlper 方法,但我不能,因为该块正在修改局部变量。知道如何简化吗?

4

3 回答 3

9

这听起来像你value1,可能有一些value2组合含义。因此,将它们封装到一个单独的类中,此时您可以调用一个方法来修改现有实例或返回该类的新实例。无论哪种方式,使用单个局部变量都可以。value3

于 2012-06-10T19:17:58.937 回答
0

您可以重构您的代码以分解一个方法,将您需要的所有内容传递给该方法,但您需要引入一些私有字段。:

   私有int值1,值2,值3;

private void doIt(int index, int threshold) {
    if (array[index] <= threshold)
        return;
    ... //Same long code modifies value1, value2, value3
}

然后将您的主要代码替换为:

void doSth(int[] array, int index1, int index2, int index3) { 
    doIt(index1, 10);
    doIt(index3, 100);
    doIt(index2, 20);
}

你完成了。

于 2012-06-10T19:26:41.327 回答
0

如果 if 语句中的代码都完全相同,为什么不这样做:

class A{
   void doSth(int[] array){
      int value1, value2, value3;
      int index[][] = {
        {val1, 10},
        {val2, 100},
        {val3, 20}
      };

      // ... 

      for(int i = 0; i < index.length; i++){
         if(array[index[i][0]] > index[i][1]){
           // ... Long code modifies value1, value2, value3
         }
      }
   }
}
于 2012-06-10T19:39:39.083 回答