Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 525
Bober02 Avatar asked May 14 '26 18:05

Bober02


1 Answers

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.

like image 59
Jon Skeet Avatar answered May 17 '26 09:05

Jon Skeet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!