java返回成功消息,从Java中的方法返回状态标志和消息的最佳方式

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值