This might be a dumb question but I'm teaching myself from a book and I noticed that a lot of examples have the print statement inside a method other than main. I was wondering if it makes a difference where you put it so I pasted the program I was working on when the question occurred to me. Would it be more efficient for me to have the getArea method print the area or leave it in main?
private static Scanner in;
private static double s;
private static double a;
public static void main(String[] args) {
in = new Scanner(System.in);
DecimalFormat two = new DecimalFormat("#.##");
System.out.println("Enter the length from center to vertex: ");
double r = in.nextDouble();
s = getSide(r);
a = getArea(s);
System.out.println("The area of a pentagon of radius "+r+" is "+two.format(a));
}
public static double getSide(double radius){
double side = 2 * radius * Math.sin((Math.PI) / 5);
return side;
}
public static double getArea(double side){
double area = (5 * Math.pow(side, 2)) / (4 * Math.tan((Math.PI) / 5));
return area;
}
As a rule of thumb I think it's good to avoid adding print statement in functions, unless the explicit purpose of the function is to print something out. In all other cases, a function should return a value.
Use the PRINT statement to send data to the screen, a line printer, or another print file. The ON clause specifies the logical print channel to use for output.
Yes, it does. The return value is what will print. Yes but as a “call” they aren't asking for a call in the context of a print function, they want you to “call” the defined parent function “calculate_age()”… As noted above, print(calculate_age(1970)) absolutely does involve a function call.
There is no difference in efficiency. This can be seen by the fact that a function can't find out what other function called it. It can't possibly behave in a different way. (Except for stack introspection and inlining...)
Architecturally it is better to try to keep methods pure in the sense that they do not cause side-effects if that is not required. That makes the program simpler to understand. A pure function takes some values and returns a value without changing anything else. Printing is a side-effect so try to keep it out of computation-style functions.
Print operation is a simple logging feature and it has no any performance penalties/benefits. Whenever you write code you can ask next questions to yourself:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With