• Post Reply Bookmark Topic Watch Topic
  • New Topic

is this code viable??  RSS feed

 
Jignesh Gohel
Ranch Hand
Posts: 276
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello,

Please tell me if the code i have provided below is viable ??
Does passing PrintWriter object reference to a method is okay practically.
I have a scenario in which i have to write different data based on some conditions but to the same PrintWriter object.The logic is same for all the conditions.So to reduce code repitition i have build a common method and passed the PrintWriter object reference and the required parameters to that method.And it is working fine.But i am closing the PrintWriter object in the same method from where i opened it.

 
Jesper de Jong
Java Cowboy
Sheriff
Posts: 16059
88
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There's nothing wrong with your code. It's perfectly alright to pass a PrintWriter to a method.

I'm not sure what exactly you mean by "viable". Can you please explain in more detail about which aspect of your code you are unsure?
 
Jeanne Boyarsky
author & internet detective
Marshal
Posts: 37469
539
Eclipse IDE Java VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Jignesh Gohel:
But i am closing the PrintWriter object in the same method from where i opened it.

Yes. This is good practice. Whomever opens a resource should be responsible for making sure it gets closed.
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you think a bit more object oriented, you could move the code out of the static main and into a member method and move the writer to a member variable.

The writeData method can use the member variable theWriter so you don't have to pass it around. Note that you can call runTest() with no argument to have it create a default writer, or you can call runTest(Writer) to write to any PrintWriter. That lets a future program reuse this class to write to a socket or a StringBuffer or whatever might come up one day.

All of this is likely not needed for your current assignment or task, but maybe it will give you some ideas down the road.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!