Reputation: 3086
I have this big class I created, as part of a project I got for homework.
The class contains data members as well as some methods, and now I need to create another (almost) identical class.
it is almost identical, because the only difference is a constant number that appears here and there in the code.
for example, if the original class has:
for (int i=0; i<8; i++) {
for (int j=0; j<8; j++) {
labels[i][j]=new Label(panel, SWT.SHADOW_OUT);
labels[i][j].setImage(empty);
}
}
the new class should have:
for (int i=0; i<10; i++) {
for (int j=0; j<10; j++) {
labels[i][j]=new Label(panel, SWT.SHADOW_OUT);
labels[i][j].setImage(empty);
}
}
and if the original class has:
labels=new Label[8][8];
the new class should have:
labels=new Label[10][10];
meaning the only difference is 10 instead of 8, several times in the code.
In what way can I reuse the code here?
Does anyone have some idea?
Upvotes: 1
Views: 121
Reputation: 53829
Simply use class attributes:
public class MyClass {
private final int labelsSize;
private final Label[][] labels;
public MyClass(final int labelsSize) {
this.labelsSize = labelsSize;
this.labels = new Label[labelsSize][labelsSize];
}
// ...
for (int i=0; i<labelsSize; i++) {
for (int j=0; j<labelsSize; j++) {
labels[i][j]=new Label(panel, SWT.SHADOW_OUT);
labels[i][j].setImage(empty);
}
}
}
Upvotes: 5
Reputation: 2103
You could pass in that number (either 8 or 10) as a parameter for this method, or as an argument for the constructor. Then set it as an instance variable and access it in this code.
Upvotes: 2