简体   繁体   中英

Should I use a method that returns a value and then print the return value in main or just include a print statement in the method?

So, say I have a method that does a calculation and I want to print the result. Is it preferrable to make the method return an integer value like:

public int addTwoNumbers(){
     .........
     return result;

}

And then I could print it using a sysout statement in the main method or should i just put a print out statement inside the the method and make it a return type of void.

public void addTwoNumbers(){
        ...........
        System.out.println(result);

}

This is a topic of great importance and lengthy theories which you can read about. Look for "Clean Code" (originally a book by Robert Martin).

However, a short practical answer would be - return the value. If a function is supposed to "Add Two Numbers" it should make this sum available to the caller, and it shouldn't do printing.

That will allow (for example...) to add 3 numbers, by making 2 calls to AddTwoNumbers .

Function's name should describe what it does. In your case addTwoNumbers should just add two numbers and nothing more. Rule of thumb: functions should do only one thing (I recommend you to read great book "Clean code"). In the second case more appropriate name would be printSumOfNumbers . Moreover the first method is slightly more universal because you can use the reuslt in any way you want in the future, not only print it to the console.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM