title: Determine method success when the return value is not a boolean
body: <p>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.</p>
  
  <p>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?</p>
  
  <p>Consider the following java code: </p>
  
  <pre><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;
  }
  </code></pre>
  
  <p>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:</p>
  
  <pre><code>JSONObject result = x.toJSONObjectForServer();
      if (result.has(KEY_TASKTYPE))
           // method success
      else // method failure
  </code></pre>
  
  <p>Handling results in such a way is not self-explanatory. I could define a new class for every return type:</p>
  
  <pre><code>public class JSONObjectForServerResult { 
      private JSONObject _object;
      private boolean _result;
  
      public JSONObject getObject { return _object; }
      public boolean getResult { return _result; } 
  
      // ctor
  }
  </code></pre>
  
  <p>and then have the caller like this:</p>
  
  <pre><code>    // some method
      JSONObjectForServerResult forServerResult = x.toJSONObjectForServer();
      if (forServerResult.getResult())
           // method success
      else // method failure
  </code></pre>
  
  <p>But this seems convoluted and a lot of work.</p>
  
  <p>Is there something I am missing when it comes to control flow/error handling in this way?</p>
  
  <p>Thanks!</p>