Search code examples
javaclassprintingprogram-entry-point

What is the proper way to print to user in Java


My computer science teachers have told me that I should not be printing strings from methods such as getters and that I should be printing from the main method to the user. I was wondering if it mattered where I print from and what is the proper way to structure my 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;
    }
}

as opposed to how my teacher says 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 are not really printing anything in your getters, just that you are obscuring the data types. A balance of an account (not really a bank) is presumably a numeric type (int, long) and not a String.

    In general, let your methods do one thing right. By printing something in your getter and returning is okay for debugging, but not advisable in general. And that's what your teacher means.

    Writing classes that have well-defined and type-safe API is useful and important especially in Java.