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? :)
Java doesn't support multi-value returns.
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.
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.
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.
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>
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With