Question

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!

Was it helpful?

Solution 2

You can, as the other answer suggested, simply use exception handling to signal when something went wrong and there is no result. This is in fact what exceptions were designed for.

However, in some languages, including Java 8, there is mechanism similar to what you're proposing as a "new class for every return type", but done generically, so that you don't have to code it yourself and you don't need a new one for every type.

In Haskell, this is the Maybe monad. In Scala it is Option, and in Java 8, it is Optional.

OTHER TIPS

I don't understand why you are catching the exception in the first place. Can you not throw the JSONException and let the caller deal with the error?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top