Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best practice for returning multiple values in Java?

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? :)

like image 464
TinusSky Avatar asked May 17 '13 12:05

TinusSky


People also ask

Can Java have multiple return values?

Java doesn't support multi-value returns.

How can I return multiple values?

We can return more than one values from a function by using the method called “call by address”, or “call by reference”. In the invoker function, we will use two variables to store the results, and the function will take pointer type data. So we have to pass the address of the data.

Which method type can return multiple type of values?

2. Using Arrays. Arrays can be used to return both primitive and reference data types. Here we've defined the coordinates array of type Number because it's the common class between Integer and Double elements.

How do you pass multiple values in an array Java?

Use a simple array (or List) of objects: public class Place { private String name; private String icon; private int distance; // constructor, methods skipped for brevity } ... private Place[] places = new Place[10]; // or private List<Place> places = new ArrayList<Place>(); Java is an OO language.


2 Answers

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>

like image 114
gma Avatar answered Sep 18 '22 13:09

gma


Not sure about "best practice" but a pragmatic option is to return a Map<String, String>? E.g.

myMap.put("result", "success"); myMap.put("usernameConfirmed", "bigTom");  return myMap; 

Probably flies in the face of a million OO principles but I hear you re wanting to avoid a proliferation of result classes.

You could alternatively use Map<String, Object> and be stricter with type checks on stored objects: Strings, Booleans, Dates, etc.

like image 32
Brian Avatar answered Sep 17 '22 13:09

Brian