Search code examples
javaobjectreturnpass-by-referencepass-by-value

What is the difference between these two methods


These two methods calculate the derivative of a monom, but I dont understand what is the difference between them, do they do the same thing? why does one have a return and the other one makes changes to the calling object? Which one is better? In general, how should I return objects?

public Monom Der()
{
    double a = this.get_coef() * this.get_pow();
    int b = this.get_pow() - 1;
    return new Monom(a, b);
}

public void Der()
{
        this.set_coefficient(this._power * this._coefficient);
        this.set_power(this._power - 1);
}

Solution

  • This one

    public Monom Der() {
        double a = this.get_coef() * this.get_pow();
        int b = this.get_pow() - 1;
        return new Monom(a, b);
    }
    

    does not change the state of the instance, it is useful when you want to have immutable objects. It can be used to work with both states the initial state and the state after process

    Monom initialMonom = new Monom(2, 2);
    Monom theNewMonom = initialMonom.Der();
    // do something with both initialMonom and theNewMonom
    

    This one

    public void Der() {
        this.set_coefficient(this._power * this._coefficient);
        this.set_power(this._power - 1);
    }
    

    changes the state of the current instance, so the instance is NOT immutable. It can be useful when the instance needs to be reused

    Monom initialMonom = new Monom(2, 2);
    // do something with initial monom
    initialMonom.Der(); // mutate the initial monom
    // do something with the new state