在Java中返回多个值的最佳实践? [英] Best practice for returning multiple values in Java?

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

问题描述

今天,我在登录表单后添加了额外的安全检查,以减缓暴力攻击。我有多个登录表单,并且做了一个很好的调用函数来完成所有的检查,然后返回结果。

  public static ValidateLoginResult validateLogin(HttpServletRequest request,String email,String password){

问题是结果没有一个值,结果是:

pre $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $' $ b

为此,我创建了一个新类。这一切都正常。



但我经常有方便的实用函数返回多个值,并开始发现有点讨厌每次为结果创建一个新类。

有没有更好的方式来返回多个值?或者我只是懒惰? :)

解决方案

不,这种结构在Java中并不存在,但你可以看看 JavaTuples库可以满足您的需求,并提供一个非常优雅的解决方案。使用三元组<布尔,字符串,布尔>


Today I've added a extra security check behind my login forms, to slow down brute force attacks. I've got multiple login forms and made a nice easy to call function that does all the checking and then returns the result.

public static ValidateLoginResult validateLogin(HttpServletRequest request, String email, String password) {

The problem is the result is not a single value, the result consists of:

boolean ok
String errorMessage
boolean displayCaptcha

For this I created a new class. This all works fine.

But I often have handy utility functions that return multiple values and start to find it a bit annoying to create a new class for the result every time.

Is there a better way of returning multiple values? Or am I just lazy? :)

解决方案

No, this kind of structure doesn't exists nativily in Java, but you can look at JavaTuples library that may suit your need and provide a quite elegant solution. Using a Triplet<Boolean, String, Boolean>

这篇关于在Java中返回多个值的最佳实践?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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