Reputation: 577
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.
Upvotes: 0
Views: 69
Reputation: 793
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.
Upvotes: 0
Reputation: 1436
You can try with below code
private void createControlPanel() {
int row =0;
row += initSessionControls(controlPanelGB);
row += initBidControls(controlPanelGB);
row += initSnapshotControls(controlPanelGB);
}
Upvotes: 1
Reputation: 567
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();
}
Upvotes: 1