简体   繁体   中英

Difference between the usage of void and int in this code

Currently a beginner, I wrote a simple program which uses getters and return values (current course). I'd like to ask when should I use the void solution and the int solution, if both gives me the same outcome?

I really hope the formatting isn't too terrible.

class Database {
    String name;
    int age;

    String getName() {
        return name;
    }

    int getAge() {
        return age;
    }

    int yearsPlusFifty() {
        int year = age + 50;
        return year;
    }

    void plusFifty() {
        int year2 = age + 50;
        System.out.println(year2);
    }
}

public static void main(String args[]) {

    Database person1 = new Database();
    person1.name = "Josh";
    person1.age = 30;

    int year = person1.yearsPlusFifty();
    System.out.println("The age plus 50 is: " + year);

    person1.plusFifty();
}

Use the int method (yearsPlusFifty) as that one has one responsibility - to calculate the value. Println in plusFifty is a side effect, which is not desirable. Keep the responsibilities of calculating and printing separate (makes it more reusable, testable, and easier to understand).

Basically, void should be used when your method does not return a value whereas int will be used when your method returns int value.

Now coming to your methods, they both are not same, they are doing two different things:

int yearsPlusFifty() - adding 50 and returning int value

void plusFifty() - better rename to printPlusFifty() - this method does both adding plus printing as well

int yearsPlusFifty() {//only adding and returning int value
    int year = age + 50;
    return year;
}

  void printPlusFifty() {//adding + printing
        int year2 = age + 50;
        System.out.println(year2);
    }

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