I have this problem called out by PMD (static code analyzer) more often that I would like, and would like to know how someone with more experience than me would write it. My code is functional but I find it inelegant, so I want to know how other programmers would write this piece.
The case is, in a network/IO petition I may or may not get a result from, but my parent method is not null-proof so I always have to return something. I also don't like several returns on a method.
public String getBingLocation(Coordinate... data)
{
String response = "Not Retrieved";
final Coordinate location = data[0];
JSONObject locationData;
try {
locationData = NetworkManager.getJSONResult(ApiFormatter
.generateBingMapsReverseGeocodingURL(location.Latitude, location.Longitude));
if (null != locationData) {
final String address = this.getAddressFromJSONObject(locationData);
response = address;
}
} catch (final ClientProtocolException e) {
LoggerFactory.consoleLogger().printStackTrace(e);
return response;
} catch (final JSONException e) {
LoggerFactory.consoleLogger().printStackTrace(e);
return response;
} catch (final IOException e) {
LoggerFactory.consoleLogger().printStackTrace(e);
return response;
} finally {
location.Street = response;
}
return response;
}
Other example:
public static Object loadObject(final String fileName, final Context context) {
Object object = null;
try {
ObjectInputStream objectInputStream = null;
try {
final FileInputStream fileStream = context.openFileInput(fileName);
objectInputStream = new ObjectInputStream(fileStream);
object = objectInputStream.readObject();
} catch (final ClassNotFoundException catchException) {
LoggerFactory.consoleLogger().printStackTrace(catchException);
} catch (final ClassCastException catchException) {
LoggerFactory.consoleLogger().printStackTrace(catchException);
} catch (final Exception catchException) {
LoggerFactory.consoleLogger().printStackTrace(catchException);
} finally {
if (objectInputStream != null) {
objectInputStream.close();
}
}
} catch (final IOException catchException) {
LoggerFactory.consoleLogger().printStackTrace(catchException);
}
return object;
}
