I have some "confusion" about void and return. In general, I understand void is used in methods without returning anything, and return is used in methods when I want to return something to the calling code.
But in the following code, I can use both, and my question is, which one to use? And how to determine? Is it about performance?
Normally, I have the same results in both cases.
public class Calc {
private double number;
Calc (double n)
{
number = n;
}
public void add(double n)
{
number += n;
}
public double add1(double n)
{
return number = number + n;
}
}
Thank you!
This method :
public void add(double n)
{
number += n;
}
You change the internal state of number
but the caller of this method doesn't know the final value of number
.
In the below method, you are intimating the caller the final value of number
.
public double add1(double n)
{
return number = number + n;
}
I would suggest to keep a separate getNumber()
getter method.