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

查看:16
本文介绍了在考虑多个条件的方法中返回 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?

谢谢

推荐答案

您正在描述编程时非常常见的场景.您打算让某件事永远不会发生,但编译器也知道它可能发生.处理此类代码路径的正确方法是确保永远不会到达它们,通常通过抛出 AssertionErrorRuntimeException 例如 IllegalArgumentException, IllegalStateExceptionUnsupportedOperationException.这称为 快速失败.

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 因为这显然是发生了什么 - 你的方法需要两个输入;其他任何事情都是禁止的,在这种情况下你应该快速失败.Effective Java Item 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.

您还可以通过其他方式避免此问题 - 即通过定义更好的方法签名.看起来您正在定义一个 "stringly-typed" 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.

在极少数情况下(通常是在直接处理用户输入时),您会想要软故障而不是快速故障.这在确认对话框中很常见;如果您要求用户输入是"或否",通常只需检查他们是否输入是"就足够了 - 无论他们输入否"还是Uhhhh",您只需将其视为不是"-是".

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天全站免登陆