Best practices for Java methods to return multiple values?

See English answers > how to return multiple objects from a Java method? twenty-three

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... }

Is there any more possibility that I may have missed it? Anyone can comment on everyone's pros and cons (ideally best used in most cases)?

Solution

Generally speaking, according to the specific situation, I will go to layer 4 or map, but if you need to return multiple irrelevant values, I think you have a serious design problem (check https://en.wikipedia.org/wiki/Single_responsibility_principle )

In specific cases (after your comments), I will definitely use the fourth modeling response with all the required fields Perhaps you can also subtype using responsesuccessful and responsefailure

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>