从Java中的方法返回状态标志和消息的最佳方式 [英] Best way to return status flag and message from a method in Java

查看:169
本文介绍了从Java中的方法返回状态标志和消息的最佳方式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的欺骗性场景,我想要一个简单的解决方案,但是最正确或大多数Java是不明显的。



我在一些类中有一个小的验证(客户端客户端)方法。验证可能会由于多种原因而失败,我想为控制流返回一个简单的布尔值,但也为用户返回一个String消息。这些是我可以想到的可能性:




  • 返回一个布尔值,并传递一个StringBuilder来收集消息。这是最接近于C风格的方式。

  • 抛出异常,而不是返回false,并包含消息。我不喜欢这个,因为失败不是例外。

  • 使用布尔值和String创建一个名为AuthenticationStatus的新类。对于一个小的方法来说,这似乎是过分的。

  • 将消息存储在成员变量中。这将引入一个潜在的竞争条件,我不喜欢这意味着一些状态不是真的存在。



任何其他建议?



修改关闭此选项




  • 返回null成功 - 这是不安全的吗?



修改解决方案:



我去了最OO的解决方案,并创建了一个小的AuthenticationResult类。我不会用任何其他语言,但我喜欢它在Java。我也喜欢返回String []的建议
,因为它像null返回但更安全。 Result类的一个优点是,如果需要,您可以获得更多详细信息的成功消息。

解决方案

返回一个小对象布尔标志和String里面都可能是最像OO的方式,尽管我同意这样一个简单的例子似乎是过度的。



另一个替代方法是始终返回一个String,并且具有null(或一个空String - 你选择哪个)表示成功。只要返回值在javadoc中清楚地解释,就不应该有任何混淆。


I have a deceptively simple scenario, and I want a simple solution, but it's not obvious which is "most correct" or "most 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.

Any other suggestions?

Edit Missed this option off

  • Return null for success - Is this unsafe?

Edit Solution:

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.

解决方案

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.

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.

这篇关于从Java中的方法返回状态标志和消息的最佳方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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