multiple return values : Java Glossary
- multiple return values
You can pass multiple parameters to a method, how do you get multiple values back?
Here are four methods:
- The official way is to invent a new class with fields for each value with
getters and setters for each field. With a decent IDE (Integrated Development Environment)
like IntelliJ Idea, this is fairly
painless. You return an object of this new class from your method. Sun uses this
technique with Point, Dimension and Location. If you
can’t think of a good inclusive English name for this new class, then these
two values are not logically related and you should not be writing a method to
return multiple fields at once.
- the quick and dirty way, you return an array of heterogeneous objects e.g.
The unboxing intValue() is automatic in
Java version 1.5 or later.
The two main reasons not to use this technique are:
- You defeat compile-time type consistency checking. If you use String (or similar specific type) instead of Object the technique is not quite as disreputable. You might
even pass in multiple arrays of different types, but that is getting ugly.
- It is not at all clear from the code which data goes in which slot.
Maintenance programmers will tend to change the assignment and fail to keep the
documentation up to date. The code is thus almost as unreadable as machine
- Pass in an Object as a parameter and have the
callee modify that Object’s fields. You will see
Sun doing this with Dimension objects, for example.
- Split the work up into several method calls. The first does the computation and
the rest retrieve but one of the results each. You can eliminate the computation
call by having the result-retriever methods check if the computation is up to date,
using lazy evaluation of the results. This is how Oracle’s GregorianCalendar works.