Bober02
Bober02

Reputation: 15351

Java - modification of local variables

I have a trivial, but irritating problem in Java. Suppose we have the following class and method:

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
        }    
    }

Disregarding what this is trying to achieve, I would like to somehow make this redundancies disappear. usually, I would pass the values to a hlper method, but I can't, since the block is modifying local variables. Any idea how to simplify this?

Upvotes: 3

Views: 202

Answers (3)

nikeairj
nikeairj

Reputation: 173

If the codes in the if statements are all exactly the same, why don't you just do it like this:

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
         }
      }
   }
}

Upvotes: 0

Bohemian
Bohemian

Reputation: 425418

You can refactor your code to break out a method into which you pass the everything you need, but you'll need to introduce some private fields.:

   private int value1, value2, value3;

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

then replace your main code to this:

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

And you're done.

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1503839

It sounds like you value1, value2 and value3 probably have some meaning in combination. So encapsulate them into a separate class, and at that point you can call a method which either modifies an existing instance or returns a new instance of that class. Either way, with a single local variable you'll be fine.

Upvotes: 9

Related Questions