从 Java 中的方法返回状态标志和消息的最佳方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/356248/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Best way to return status flag and message from a method in Java
提问by Draemon
I have a deceptively simple scenario, and I want a simple solution, but it's not obvious which is "most correct" or "most Java".
我有一个看似简单的场景,我想要一个简单的解决方案,但不清楚哪个是“最正确”或“最 Java”。
Let's say I have a small authenticate(Client client) method in some class. The authentication could fail for a number of reasons, and I want to return a simple boolean for control flow, but also return a String message for the user. These are the possibilities I can think of:
假设我在某个类中有一个小的身份验证(客户端客户端)方法。由于多种原因,身份验证可能会失败,我想为控制流返回一个简单的布尔值,但也为用户返回一个字符串消息。这些是我能想到的可能性:
- Return a boolean, and pass in a StringBuilder to collect the message. This is the closest to a C-style way of doing it.
- Throw an exception instead of returning false, and include the message. I don't like this since failure is not exceptional.
- Create a new class called AuthenticationStatus with the boolean and the String. This seems like overkill for one small method.
- Store the message in a member variable. This would introduce a potential race condition, and I don't like that it implies some state that isn't really there.
- 返回一个布尔值,并传入一个 StringBuilder 来收集消息。这是最接近 C 风格的方法。
- 抛出异常而不是返回 false,并包含消息。我不喜欢这样,因为失败并不例外。
- 使用布尔值和字符串创建一个名为 AuthenticationStatus 的新类。对于一个小方法来说,这似乎有点矫枉过正。
- 将消息存储在成员变量中。这会引入潜在的竞争条件,我不喜欢它暗示某种并不真正存在的状态。
Any other suggestions?
还有其他建议吗?
EditMissed this option off
编辑错过了这个选项
- Return null for success - Is this unsafe?
- 成功返回 null - 这不安全吗?
EditSolution:
编辑解决方案:
I went for the most OO solution and created a small AuthenticationResult class. I wouldn't do this in any other language, but I like it in Java. I also liked the suggestion of returning an String[] since it's like the null return but safer. One advantage of the Result class is that you can have a success message with further details if required.
我选择了最面向对象的解决方案并创建了一个小的 AuthenticationResult 类。我不会用任何其他语言来做这件事,但我喜欢用 Java 来做。我也喜欢返回 String[] 的建议,因为它类似于 null 返回但更安全。Result 类的一个优点是,如果需要,您可以获得包含更多详细信息的成功消息。
采纳答案by Ashley Mercer
Returning a small object with both the boolean flag and the String inside is probably the most OO-like way of doing it, although I agree that it seems overkill for a simple case like this.
返回一个包含布尔标志和字符串的小对象可能是最像 OO 的方式,尽管我同意对于像这样的简单案例来说这似乎有点矫枉过正。
Another alternative is to always return a String, and have null (or an empty String - you choose which) indicate success. As long as the return values are clearly explained in the javadocs there shouldn't be any confusion.
另一种选择是始终返回一个字符串,并使用 null(或空字符串 - 您选择哪个)表示成功。只要在 javadocs 中清楚地解释了返回值,就不应该有任何混淆。
回答by sblundy
You could return a Collection of error messages, empty indicating that there were no problems. This is a refinement of your third suggestion.
您可以返回错误消息集合,空表示没有问题。这是对您的第三个建议的改进。
回答by Gishu
How about returning a string. Empty or Null for success. Error Message in case of failure. Simplest that would work. However not sure if it reads well.
返回一个字符串怎么样。为空或 Null 表示成功。失败时的错误消息。最简单的方法。但是不确定它是否读得好。
回答by Jacob Schoen
I personally think creating a new class called AuthenticationStatus with the boolean and the String is the most Java like way. And while it seems like overkill (which it may well be) it seems cleaner to me and easier to understand.
我个人认为使用布尔值和字符串创建一个名为 AuthenticationStatus 的新类是最像 Java 的方式。虽然这看起来有点矫枉过正(这很可能是),但对我来说似乎更清晰,更容易理解。
回答by Paul Tomblin
I use the "tiny class" myself, usually with an inner class. I don't like using arguments to collect messages.
我自己使用“小类”,通常使用内部类。我不喜欢使用参数来收集消息。
Also, if the method that might fail is "low level" - like coming from an app server or the database layer, I'd prefer to return an Enum with the return status, and then translate that into a string at the GUI level. Don't pass around user strings at the low level if you're ever going to internationalize your code, because then your app server can only respond in one language at a time, rather than having different clients working in different languages.
此外,如果可能失败的方法是“低级别”的——比如来自应用服务器或数据库层,我更愿意返回一个带有返回状态的 Enum,然后在 GUI 级别将其转换为字符串。如果您打算将代码国际化,请不要在低级别传递用户字符串,因为这样您的应用服务器一次只能以一种语言响应,而不是让不同的客户端使用不同的语言工作。
回答by Michael Borgwardt
Is this the only method where you have such a requirement? If not, just generate a general Response class with an isSuccessful flag and a message string, and use that everywhere.
这是您有这种要求的唯一方法吗?如果没有,只需生成一个带有 isSuccessful 标志和消息字符串的通用 Response 类,并在任何地方使用它。
Or you could just have the method return null to show success (not pretty, and does not allow returning a success AND a message).
或者你可以让方法返回 null 来显示成功(不漂亮,并且不允许返回成功和消息)。
回答by adam
You could use exceptions....
您可以使用异常....
try {
AuthenticateMethod();
} catch (AuthenticateError ae) {
// Display ae.getMessage() to user..
System.out.println(ae.getMessage());
//ae.printStackTrace();
}
and then if an error occurs in your AuthenticateMethod you send a new AuthenticateError (extends Exception)
然后如果您的 AuthenticateMethod 发生错误,您将发送一个新的 AuthenticateError (扩展异常)
回答by Bas Leijdekkers
Some more options:
还有一些选择:
- Return an separate enum value for each type of failure. The enum object could contain the message
- Return an int and have a separate method that looks up the appropriate message from an array
- create a generic utility tuple class that can contains two values. Such a class can be useful in many more places.
- 为每种类型的失败返回一个单独的枚举值。枚举对象可以包含消息
- 返回一个 int 并有一个单独的方法从数组中查找适当的消息
- 创建一个可以包含两个值的通用实用程序元组类。这样的类可以在更多地方使用。
simple tuple example, actual implementation may need more:
简单的元组示例,实际实现可能需要更多:
class Tuple<L, R> {
public final L left;
public final R right;
public Tuple( L left, R right) {
this.left = left;
this.right = right;
}
}
回答by bruno conde
I would choose the Exception option in first place.
我会首先选择 Exception 选项。
But, in second place, I would prefer the C-style technique:
但是,第二,我更喜欢 C 风格的技术:
public boolean authenticate(Client client, final StringBuilder sb) {
if (sb == null)
throw new IllegalArgumentException();
if (isOK()) {
sb.append("info message");
return true;
} else {
sb.append("error message");
return false;
}
}
This is not so strange and it's done in many places in the framework.
这并不奇怪,在框架的很多地方都这样做了。
回答by Ma99uS
Instead of creating a special object for return type, I usually just return an array where all the returned information is stored. The benefit is that you can extend this array with new elements without creating new types and mess. The downside you have to know exactly what elements should present when array is returned from particular method to parse it correctly. Usually I agree on certain structure, like first element is always Boolean indication success, second is String with description, the rest is optional. Example:
我通常只返回一个存储所有返回信息的数组,而不是为返回类型创建一个特殊的对象。好处是您可以使用新元素扩展此数组,而无需创建新类型和混乱。不利的一面是,当从特定方法返回数组以正确解析它时,您必须确切知道应该显示哪些元素。通常我同意某些结构,比如第一个元素总是布尔指示成功,第二个是带有描述的字符串,其余的都是可选的。例子:
public static void main(String[] args)
{
Object[] result = methodReturningStatus();
if(!(Boolean)result[0])
System.out.println("Method return: "+ result[1]);
}
static Object[] methodReturningStatus()
{
Object[] result = new Object[2];
result[0] = false;
result[1] = "Error happened";
return result;
}