What is the correct way to print to users in Java

My computer science teacher told me that I should not print strings from getter and other methods, and I should print strings from main method to users I want to know if what I print is important and what is the right way to build the code

For example:

public class Main {
    public static void main(String[] args) throws IOException {
        Bank bank = new Bank(20);
        System.out.println(bank.getBalance());
    }
}

public class Bank {
    int balance;

    public Bank(int balance){
        this.balance = balance;
    }

    public String getBalance(){
        return "You have $" + this.balance;
    }
}

Instead of my teacher saying I should write it

public class Main {
    public static void main(String[] args) throws IOException {
        Bank bank = new Bank(20);
        System.out.println("You have $" + bank.getBalance());
    }
}

public class Bank{
    int balance;

    public Bank(int balance){
        this.balance = balance;
    }

    public int getBalance(){
        return this.balance;
    }
}

Solution

Your teacher is right

You didn't actually print anything in the getter, just because you blurred the data type The balance of an account (not a real bank) may be numeric (int, long) rather than string

Generally speaking, let your method do the right thing You can debug by printing something in the getter and returning it, but it is generally not advisable That's what your teacher means

It is useful and important to write classes with well - defined and type - safe APIs, especially in Java

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>