在考虑多个条件的方法中返回null [英] Returning null in a method that accounts for multiple conditions

查看:91
本文介绍了在考虑多个条件的方法中返回null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑以下方法:

private static String method (String string) {
    if (string.equals("conditionOne")) {
        return value;
    } else if (string.equals("conditionTwo")) {
        return symbol;
    } else {
        return null;
    }
}

比方说,我正在检查两个条件,conditionOneconditionTwo.同样,假设程序的其他部分确保只有这两种情况才会发生.由于该方法必须在所有情况下都返回某种值以避免编译器错误,因此仅出于语法目的,可以为最终的else块返回null吗,因为该部分将永远不会执行?

Let's say I am checking for two conditions, conditionOne and conditionTwo. Also, assume that some other part of the program ensures that only these two cases will ever happen. Since the method has to return something for all cases to avoid a compiler error, is it okay to return null for the final else block just for syntactical purposes since that part will never execute?

编辑:为清楚起见,如果我不包括最后一个else块,则编译器会给我一个错误(期望返回语句").除了返回null(或下面的Anthony指出的空字符串)之外,还有另一种方法可以编写此方法,以免发生这种情况吗?

Edit: For clarity, I'd like to mention that the compiler gives me an error ("Expecting return statement") if I don't include that last else block. Other than to returning null (or an empty string, as pointed out by Anthony below), is there another way to write this method so that this does not happen?

谢谢

推荐答案

您正在描述编程时的一个非常常见的场景.您打算某件事永远不会发生,但是编译器也知道它可能发生.处理此类代码路径的正确方法通常是通过抛出 IllegalStateException 失败.

You're describing a very common scenario while programming. You intend for a certain thing to never happen, but the compiler also knows it could happen. The proper way to handle such code paths is to ensure that they are never reached, generally by throwing an AssertionError or a RuntimeException such as IllegalArgumentException, IllegalStateException or UnsupportedOperationException. This is referred to as failing-fast.

在您的情况下,我将抛出一个IllegalArgumentException,因为这很清楚发生了什么-您的方法需要两个输入;禁止其他任何事情,在这种情况下,您应该快速失败.有效的Java项目38也对此进行了讨论.

In your case I would throw an IllegalArgumentException as that's clearly what's happened - your method expects exactly two inputs; anything else is forbidden and you should fail-fast in such cases. Effective Java Item 38 also discusses this.

private static String method (String condition) {
  if (condition.equals("conditionOne")) {
    return value;
  } else if (condition.equals("conditionTwo")) {
    return symbol;
  }
  throw new IllegalArgumentException("Invalid condition '" + condition +"'");
}

现在您可以确信,此功能将仅支持其设计要支持的输入.更好的是,任何人错误地调用您的方法都将收到清晰,可操作的错误消息.

Now you can be confident the only inputs this function will support are the ones it is designed to support. Even better, anyone calling your method incorrectly will get a clear, actionable error message.

《 Guava用户指南》具有很好的各种故障概述,你应该把它们举起来.

The Guava User Guide has a good overview of different kinds of failures and when you should raise them.

您还可以通过其他方式避免此问题-即通过定义更好的方法签名.似乎您正在定义字符串类型" API;使用枚举将有助于防止调用者传递错误的参数.另请参见有效Java项目50和30.

You could also avoid this issue other ways - namely by defining a better method signature. It looks like you're defining a "stringly-typed" API; using an enum would help prevent callers from passing in erroneous parameters. See also Effective Java Items 50 and 30.

在极少数情况下(通常在直接与用户输入打交道时),您会希望自动失败而不是快速失败.这在确认对话框中很常见;如果您要求用户输入是"或否",通常只需检查他们是否输入是"就足够了-他们是否输入了否"或嗯",您只会将其视为不是-是"

In rare cases (generally when dealing directly with user input) you'll want to fail-soft rather than fail-fast. This is common with confirmation dialogs; if you ask the user to enter "Yes" or "No" it's generally sufficient to simply check whether they entered "Yes" - whether they entered "No" or "Uhhhh", you'll just treat it as not-"Yes".

这篇关于在考虑多个条件的方法中返回null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆