I am working on a basic ATM project. I have an account class that has several methods including a getBalance method. The getBalance method returns a double value. However, I want it to print some text prior to returning the value. This is how I have it set up:
public double getBalance() {
System.out.print("Your balance is: ");
return balance;
}
In my main method I just call it as:
System.out.println(account1.getBalance());
Is it bad practice to add System.out.print within my getBalance() method in this way?
It outputs everything correctly ex.: Your balance is: 1000.0
Is adding
System.out.print()
bad practice within a non-void method?
What you are doing goes against the "Separation of Concerns" design principle:
"In Computer Science, separation of concerns is a design principle for separating a computer program into distinct sections. Each section addresses a separate concern, a set of information that affects the code of a computer program."
(The above is from Wikipedia. It is difficult to come up with clear and inclusive definition of what a "concern" actually is. But with experience you will learn to recognize where different concerns are not being properly separated.)
In this case, the two concerns are "providing a way to get the balance" and "showing the balance to the user".
Here are a couple of scenarios that illustrate why that this is a bad idea:
Suppose that you want to use your getBalance()
method in a transfer(...)
operation that transfer money from one account to another. But now you will find that an inappropriate message is sent to the user when they perform a transfer.
Suppose that you want to use your getBalance()
method in a statement()
method that operation that generates a bank statement for the user. You may want the balance to be output as part of the bank statement, but the println
is likely to be formatting it the wrong way, and / or printing it in the wrong place. (You might not even want it printed to standard output.)
Note: if the print statement was for logging purposes, then doing that in a getter is not a separation of concerns issue. But if that is its purpose, you should be using a logging framework rather than System.out.print*
calls.
In summary: yes it is bad practice for a getter to also print / display information for the user.
It is also a bad idea (and incorrect per the rules of accounting) to represent money using floating point types; see Why not use Double or Float to represent currency?.