multiple return values : Java Glossary

*0-9ABCDEFGHIJKLMNOPQRSTUVWXYZ (all)

multiple return values
You can pass multiple parameters to a method, how do you get multiple values back? Here are four methods:
  1. 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.
  2. 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 language.
  3. 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.
  4. 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.

This page is posted
on the web at:

http://mindprod.com/jgloss/multiplereturn.html

Optional Replicator mirror
of mindprod.com
on local hard disk J:

J:\mindprod\jgloss\multiplereturn.html
logo
Please the feedback from other visitors, or your own feedback about the site.
Contact Roedy. Please feel free to link to this page without explicit permission.

IP:[65.110.21.43]
Your face IP:[54.211.207.116]
You are visitor number