Often I have to skip some actions on the first (or last) loop iteration. Now I need to append some arguments to a URL and separate the arguments by the &
character.
For example:
http://api.openweathermap.org/data/2.5/weather?q=London&mode=xml&cnt=7
To do so, the code looks like this:
public static String prepareUrl(String url, List<? extends NameValuePair> arguments) {
boolean firstIteration = true;
StringBuilder urlBuilder = new StringBuilder(url);
for (NameValuePair argument : arguments) {
if (firstIteration) {
firstIteration = false;
} else {
urlBuilder.append("&");
}
urlBuilder.append(argument.getName());
urlBuilder.append("=");
urlBuilder.append(argument.getValue());
}
return urlBuilder.toString();
}
But it's very annoying to write and a little difficult to read such code. And it's easy to make a mistake in a loop body like this.
I wrote the next class, but I need your help to name the class and its methods properly (I'm pretty bad in English). And please, criticize my code severely.
// I know that class name must be a noun.
// But I can't think of a good name.
// And it seems to me that a comparison with the blank cartridge is a good one.
public abstract class FirstCartridgeIsBlank implements Runnable {
private boolean firstCartridge;
public FirstCartridgeIsBlank() {
firstCartridge = true;
}
public final void run() {
if (firstCartridge) {
firstCartridge = false;
blankShot();
} else {
shot();
}
}
protected void blankShot() {
// the inheritors can override this method if they need
}
protected abstract void shot();
}
Now the method prepareUrl()
looks like this:
public static String prepareUrl(String url, List<? extends NameValuePair> arguments) {
final StringBuilder urlBuilder = new StringBuilder(url);
FirstCartridgeIsBlank appendAmpersand = new FirstCartridgeIsBlank() {
@Override
protected void shot() {
urlBuilder.append("&");
}
};
for (NameValuePair argument : arguments) {
appendAmpersand.run();
urlBuilder.append(argument.getName());
urlBuilder.append("=");
urlBuilder.append(argument.getValue());
}
return urlBuilder.toString();
}
I can't use the String.join()
method from Java 8 because it's for the Android app (i.e. Java 6).