Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best practice for a Java method returning multiple values? [duplicate]

I need a non-static instance method to return multiple values. For the sake of a simple example let's say these are boolean success and Object obj - but in the general case there could be more and they could be unrelated to each other. Can think of a few different ways of doing this:

Solution 1

private boolean aMethod(int aParam, Object obj) { ...set obj parameter & return value... }

Solution 2

private Pair<Boolean, Object> aMethod(int aParam) { ...set return pair values... }

Solution 3

private Object obj;
...
private boolean aMethod(int aParam) { ...set obj field & return value... }

Solution 4

private class MethodReturn { // Nested class - could be a separate class instead
    boolean success;
    Object obj;
    // ... Getters and setters omitted for brevity
}

private MethodReturn aMethod(int aParam) { ...set return object values... }

Are there any more possibilities I might have missed? And could anyone comment as to the pros and cons of each (and ideally, which might be the best to use under most circumstances)?

like image 826
Steve Chambers Avatar asked Jul 20 '16 12:07

Steve Chambers


People also ask

Can I return multiple values from a method in Java?

You can return only one value in Java. If needed you can return multiple values using array or an object.

How can I return multiple values from a method?

JavaScript doesn't support functions that return multiple values. However, you can wrap multiple values into an array or an object and return the array or the object. Use destructuring assignment syntax to unpack values from the array, or properties from objects.

Can a method have 2 returns?

No, you can not have two returns in a function, the first return will exit the function you will need to create an object.


1 Answers

In general I'd go for the 4th or for a Map depending by the specific case, but if you need to return multiple unrelated values, I think that you have a serious design issue (Check https://en.wikipedia.org/wiki/Single_responsibility_principle)

In the specific case (after your comment), I'd definitely go with the 4th modeling the Response with all the required fields. Possibly you can also subtype with a ResponseSuccessful and ResponseFailure.

like image 138
alros Avatar answered Sep 21 '22 13:09

alros