Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Printing in void method vs returning a value

 
Eviano Afiemo
Greenhorn
Posts: 21
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Question based on Nitpick for Assignment4
given the following example
<code>
class DoStuff
{
public static void main( String[] args )
{
..............code.....
..............code.....

System.out.println( doSomething(param) ) ;
}
static int doStuff(int param)
{

.........code......
.........code.....

return value ;
}//How about if you just print it instead of returning it."(nitpicker's comment)
}
</code>
Since it's been suggested that I print the value out in the doStuff() method,
there's obviously a good reason for doing this.
What I'd like to know is what this reason is.
Does this imply thatit is more efficient to use void methods rather than methods which return values?

Thanks in advance
Evi...
 
Johannes de Jong
tumbleweed
Bartender
Posts: 5089
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Without seeing the actual code, the only reason that I can think of is that you do it, the print, where it logically belongs.
 
Adam Vinueza
Ranch Hand
Posts: 76
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I can see what one of my nitpicks will be on Say(a) now; ironically, I originally used a void method, but then changed it to a String method. The nitpick seems reasonable, so I guess I'll be changing it back.
My own two cents is that if you're going to do something with a string after you've called someMethodOrOther() on it--say, if you need to compare the return value of someMethodOrOther() with another string--the method should return the string. But if all you're going to do with it is print it after someMethodOrOther() has done what you wanted it to do, you might as well let the method be void and insert a print command into it.
 
Eviano Afiemo
Greenhorn
Posts: 21
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for the reponses.
I guess it makes sense to print immediately if nothing else is to be done with the String in question.
I'll put Adam's suggestion in my list of things to watch out for, unless someone else thinks otherwise.
 
Pauline McNamara
Sheriff
Posts: 4012
6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Evi,
I found the following thread to be a very informative discussion about "printing on the go" as opposed to creating String variables: http://www.javaranch.com/ubb/Forum19/HTML/000471.html
Hope it helps you as it did me,
Pauline
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic