Updating original values after passing them as params to a new method instead of references

kabugh :

I have a method whose some parts of are repetitive. I managed to split the code in a way that the original method uses smaller methods many times. The problem is that when I pass some values as params to those new smaller methods and work with them, original values don't get updated. The actions I do are: value incrementation or removing items from arraylist. How do I update the original values using the smaller methods, not only the references? The only possible solution I came up with is to create a new class where I could have a setter for those values and update them. But are there easier/straightforward ways to solve it?

Part of the main method:

int numberOfBlocks = 0;
int currentBlock = 0;
int currentTime = 0;

ArrayList<Request> queue = new ArrayList<Request>();

if(queue.size != 0) {
    updateStatus(queue, currentBlock, numberOfBlocks);
}

if(something else happens) {
    removeFinished(queue, currentBlock);
}

Smaller methods:

private void updateStatus(ArrayList<Request> queue, int currentBlock, int numberOfBlocks) {
        if (queue.get(0).getBlock() > currentBlock)
            currentBlock++;
        else
            currentBlock--;

        numberOfBlocks++;
    }

private void removeFinished(ArrayList<Request> queue, int currentBlock){
        if (queue.get(0).getBlock() == currentBlock) {      
            queue.remove(0);
        }
    }
Michael Gantman :

First of all, if you pass a parameter in order for it to be changed in the method, your method should return the changed value, this will resolve your issue. If more then one value needs to be changed, then you are correct, primitives are passed y value and the invoking method doesn't see the changes made in the invoked method. So you should encapsulate those values in a wrapping class with setters and getters like you wanted to. That alone will resolve your problem. But also it would make sense for your method to return that class since it is modified. This is just a good stile

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=374242&siteId=1