简体   繁体   中英

How to avoid passing one variable from one method to another

I'm refactoring some old Java code and I'd like to know if there is a better way to refactor the following code

private void createControlPanel() {
  int row = 0;
  row = initSessionControls(controlPanelGB, row);
  row = initBidControls(controlPanelGB, row);
  row = initSnapshotControls(controlPanelGB, row);
}

row gets incremented in each method. That looks ugly to me. I also don't want to do the following

private void createControlPanel() {
  row = initSessionControls(controlPanelGB, 1);
  row = initBidControls(controlPanelGB, 2);
  row = initSnapshotControls(controlPanelGB, 3);
}

Any advice on how best to refactor this? I'm using Java 8.

I suggest using a ControlPanelFiller class:

class ControlPanelFiller {
    private final ... controlPanel;
    private int row = 0;
    public ControlPanelFiller(... controlPanel) {
        this.controlPanel = controlPanel;
    }
    public ControlPanelFiller initSessionControls() {
        ...
        ++row;
        return this;
    }
    public ControlPanelFiller initBidControls() {
        ...
        ++row;
        return this;
    }
    public ControlPanelFiller initSnapshotControls() {
        ...
        ++row;
        return this;
    }
}

private void createControlPanel()
{
    ControlPanelFiller cpf = new ControlPannelFiller(controlPanelGB);
    cpf.initSessionControls()
        .initBidControls()
        .initSnapshotControls();
}

You can try with below code

private void createControlPanel() {
int row =0;
  row += initSessionControls(controlPanelGB);
  row += initBidControls(controlPanelGB);
  row += initSnapshotControls(controlPanelGB);
}

You're right to feel uncomfortable with this code. It seems that each of the called methods knows what the next row to be processed is, so they are tightly coupled and the logic for deciding the next row is distributed across several methods. Yeuch! If the next row should indeed be 1 greater that the previous row, then it's probably better to centralize this logic in the createControlPanel method:

private void createControlPanel() {
  int initialRow = 0;
  initSessionControls(controlPanelGB, initialRow);
  initBidControls(controlPanelGB, initialRow+1);
  initSnapshotControls(controlPanelGB, initialRow+2);
}

This is clearer than your second solution above, as it's clear that the second argument is a row, and how it relates to the initial row value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM