I'm considering how to refactor code to make it clean & clear.
There are some principles to make code clean; in this case I think it's Single Responsibility and One level of abstraction.
The original code is like this:
for (int i = 0; i < header.length; i++) {
if (header[i].equals(Constant.ID)) {
indexOfID = i;
} else if (header[i].equals(Constant.NAME)) {
indexOfName = i;
} else if (header[i].equals(Constant.CATEGORY)) {
indexOfCategory = i;
}
}
Then I separated the loop into smaller functions.
private int getIndexOfColumnType(String[] header, String type) {
int index = -1;
int i = 0;
int size = header.length;
while (index < size && index < 0) {
if(header[i].equals(type)) {
index = i;
}
i++;
}
return index;
}
And call it
int indexOfID = getIndexOfColumnType(header, Constant.ID);
int indexOfName = getIndexOfColumnType(header, Constant.NAME);
int indexOfCategory = getIndexOfColumnType(header, Constant.CATEGORY);
In this way, I need to use 3 loops; so I wonder which is better for performance
because header
array can be large.
Please tell me your idea.
header
populated? \$\endgroup\$if
in your code you most likey should better use polymorphism to solve the situation. But the code you posted is way too short to give a concrete proposal. \$\endgroup\$header
is header of CSV file, so the size can be 2, 3 to ~100. \$\endgroup\$