Is it more efficient to have a print statement in a method besides the main one or does it matter?

This may be a stupid question, but I am learning from a book, and I noticed that many examples have a print statement inside a method other than the main one. I was wondering if that matters when you put it down, so I inserted the program I was working on when the question arose. Would it be more efficient for me to have the getArea method print a region or leave it mostly?

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; } 
+5
source share
2 answers

There is no difference in effectiveness. This is evidenced by the fact that the function cannot determine what other function it called. He cannot behave differently. (Except for introspection of the stack and nesting ...)

Architecturally, it is better to try to keep the methods clean in the sense that they do not cause side effects if this is not required. This simplifies the understanding of the program. A pure function takes some values ​​and returns a value without changing anything else. Printing is a side effect, so try not to use it in computational style functions.

+9
source

The print operation is a simple logging function and it does not have any penalties / benefits. Whenever you write code, you can ask yourself the following questions:

  • Should this code be used by someone else? (record should not be inserted)
  • If this code is debugged using application logs (a record must be inserted)
  • What will the message you want to print say? (What will be done is inserted before the method. The result of the execution must be inserted after the method. The execution process must be inserted in the method itself)
+1
source

All Articles