When programming I try to modularize my code into as small and focused methods as possible, sometimes this becomes a problem because if I am in some I/O loop and some method fails to get the requested data then I can't just control the flow of the return value with ease like I could if I had one big method.
Most methods remedy this by returning a boolean indicating success, but my question is, what is the best practice when it comes to success/failure of a method which returns an important object?
Consider the following java code:
public JSONObject toJSONObjectForServer() {
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put(KEY_TASKTYPE, _taskType);
jsonObject.put(KEY_TIMESTAMP, _timestamp);
jsonObject.put(KEY_TASKSCORE, _taskScore);
jsonObject.put(KEY_UNITSCONSUMED, _unitsConsumed);
} catch (JSONException e) {
e.printStackTrace();
}
return jsonObject;
}
If this fails for some reason, an empty JSONObject would be returned. deferring the error detection to the calling method, making me have to write ugly stuff like:
JSONObject result = x.toJSONObjectForServer();
if (result.has(KEY_TASKTYPE))
// method success
else // method failure
Handling results in such a way is not self-explanatory. I could define a new class for every return type:
public class JSONObjectForServerResult {
private JSONObject _object;
private boolean _result;
public JSONObject getObject { return _object; }
public boolean getResult { return _result; }
// ctor
}
and then have the caller like this:
// some method
JSONObjectForServerResult forServerResult = x.toJSONObjectForServer();
if (forServerResult.getResult())
// method success
else // method failure
But this seems convoluted and a lot of work.
Is there something I am missing when it comes to control flow/error handling in this way?
Thanks!