Steve Chambers Steve Chambers - 1 month ago 15
Java Question

Best practice for a Java method returning multiple values?

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

Answer

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.