简体   繁体   English

当返回值不是布尔值时,确定方法成功

[英]Determine method success when the return value is not a boolean

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. 在编程时我尝试将我的代码模块化为尽可能小的聚焦方法,有时这会成为一个问题,因为如果我在一些I / O循环中并且某些方法无法获取所请求的数据,那么我不能只控制流程如果我有一个很大的方法,就像我可以轻松获得返回值。

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: 考虑以下java代码:

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. 如果由于某种原因失败,将返回空的JSONObject。 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! 谢谢!

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? 你能不抛出JSONException并让调用者处理错误?

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. 但是,在某些语言中,包括Java 8,有一种机制类似于你提出的“每个返回类型的新类”,但是通常都是这样做的,所以你不必自己编写代码就可以了。每种类型都需要一个新的。

In Haskell, this is the Maybe monad . 在Haskell中,这是Maybe monad In Scala it is Option , and in Java 8, it is Optional . 在Scala中它是Option ,在Java 8中,它是Optional

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM