Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Pass or return objects???

 
alex earnshaw
Ranch Hand
Posts: 60
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Alex
 
Frank Carver
Sheriff
Posts: 6920
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
     
    alex earnshaw
    Ranch Hand
    Posts: 60
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    That's a great help thanks!
     
    • Post Reply
    • Bookmark Topic Watch Topic
    • New Topic