Best practice for returning multiple values in Java?

ⅰ亾dé卋堺 提交于 2019-11-28 08:56:04

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.

You can define a Pair<A, B> class, and a Triplet<A, B, C> class, and that would solve the problem of returning 2 and 3 values while ensuring type-safety. In this particular case, the signature could be

public static boolean validateLogin(HttpServletRequest request,
            String email, String password, Pair<Message, Boolean> outputIfOk);

Or even better, in a servlet context, it may make sense to set some well-documented request attributes.

If you find yourself needing special classes to return results very often, you can most likely refactor those clases to share a common ancestor (say, have a RequestStatus which includes the 'ok' and 'message' fields).

Other than that, yes, you are being lazy -- custom clases will always be more self-documenting than Pairs and Triplets.

I can't really think of a better, cleaner and more object-oriented way of returning multiple values from a function than encapsulating them in a class.

Ideally, the multiple values you want to return are conceptually all part of the same class, so it makes sense to group them this way; if they don't, then you should probably decompose your function in some smaller functions that return each of the values you need outside of the function itself.

As far as I can tell, some IDEs also have facilities to help encapsulating multiple values in a class: for instance, Eclipse has Refactor --> Extract class...

You can return an Object[] array, java autoboxes so its more easy to use. If it's just for a short distance handover, why not. Ofc its risky, possible class cast trouble, nullchecks etc

but its easy to write and use.

then again, a static inner class is quickly created and if you put it right next to the method returning it, you also know where to find it (usually near the origin)

I'd probably just go the class route myself, but depending on what you want the function to return, you might be able to get away with returning some sort of container of values.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!