File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes Pass or return objects??? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Pass or return objects???" Watch "Pass or return objects???" New topic

Pass or return objects???

alex earnshaw
Ranch Hand

Joined: Nov 05, 2001
Posts: 60
In some legacy code I have a method called getObjects which accepts a Hashtable as an argument. Inside the method the Hashtable is populated with the objects, making use of 'pass by value' I believe. The method returns void.
However, I think it would be simpler for the method to take no arguments and return a Hashtable of the objects.
Can anyone tell me what are the advantages/disadvantages of passing an object into a method and modifying its contents as opposed to returning the object directly?
First way:

Second way:

Which way is better
Thanks in advance
Frank Carver

Joined: Jan 07, 1999
Posts: 6920
The first option has at least the following advantages:
  • the (commmon?) case where you only want the Hashtable to contain the new items is simpler
  • You'll never need to remember to "clean out" an existing Hashtable before passing it in to the method

  • The second option has at least the following advantages:
  • You can preload default values into the Hashtable for items which might not be present
  • You can call the method repeatedly to accumulate/update values.
  • Fewer Hashtable objects are created, which can mean lower memory usage and faster garbage collection.
  • It can be easier to test in isolation using MockObjects (it would be even easier if the input type was Map, rather than specifically a Hashtable).
  • [list]This approach can easily emulate the other approach:

    [ July 16, 2002: Message edited by: Frank Carver ]

    Read about me at ~ Raspberry Alpha Omega ~ Frank's Punchbarrel Blog
    alex earnshaw
    Ranch Hand

    Joined: Nov 05, 2001
    Posts: 60
    That's a great help thanks!
    I agree. Here's the link:
    subject: Pass or return objects???
    It's not a secret anymore!