Search code examples
javamethodsreturn

Void method for println vs. println with return method


While I was writing a calculator app, I just couldn't figure out what the best way to do this is:

private void calculate(String command) {
    System.out.print("value1: ");
    int value1 = reader.readInteger();
    System.out.print("value2: ");
    int value2 = reader.readInteger();

    if (command.equals("sum"))
        System.out.println("sum of the values " + sum(value1 + value2));
}

private int sum(int value1, int value2) {
    return value1 + value2;
}

or

private void calculate(String command) {
    System.out.print("value1: ");
    int value1 = reader.readInteger();
    System.out.print("value2: ");
    int value2 = reader.readInteger();

    if (command.equals("sum"))
        sum();
}

private void sum(int value1, int value2) {
    System.out.println("sum of the values " + value1 + value2);
}

The second one makes the calculate() method cleaner, but is it generally preferred to use return methods or void(just for the printline)?


Solution

  • In general, it's better to return value - then you can test your method and reuse it in more complex calculations.

    One of the good approaches is to define some calculate method which calculates and returns value, and define void show method which will accept as argument value to show on the screen and properly show it.