Consider the following code
1
2
3
4
5
6
7
8
9
10
| public static <T> String join(Iterator<T> itr, String seperator) {
StringBuilder sb = new StringBuilder();
while (itr.hasNext()) {
if (sb.length() != 0) {
sb.append(separator);
}
sb.append(itr.next().toString());
}
return sb.toString();
} |
public static <T> String join(Iterator<T> itr, String seperator) {
StringBuilder sb = new StringBuilder();
while (itr.hasNext()) {
if (sb.length() != 0) {
sb.append(separator);
}
sb.append(itr.next().toString());
}
return sb.toString();
}
When I read through this code, checking StringBuffer’s length and then appending a separator does not communicate the intent very well.
4
5
6
| if (sb.length() != 0) {
sb.append(separator);
} |
if (sb.length() != 0) {
sb.append(separator);
}
Here we are relying on the side-effect (StringBuffer’s length) instead of asking the iterator. So the code does not flow smoothly. Also, now if you want to add a prefix to the joined String this logic might break.
IMHO, following code solves this problem.
1
2
3
4
5
6
7
8
9
10
| public static <T> String join(Iterator<T> itr, String seperator) {
StringBuilder sb = new StringBuilder();
while (itr.hasNext()) {
sb.append(itr.next().toString());
if(itr.hasNext()) {
sb.append(separator);
}
}
return sb.toString();
} |
public static <T> String join(Iterator<T> itr, String seperator) {
StringBuilder sb = new StringBuilder();
while (itr.hasNext()) {
sb.append(itr.next().toString());
if(itr.hasNext()) {
sb.append(separator);
}
}
return sb.toString();
}