How can I cut down on those console.?

Hey there!

I was doing the Mortgage Calculator and found out I had a very repetitive pattern on the CalculateMortgage class. Let me just show you:

package me.oriol;

public class MortgageCalculator {

    private final Console console = new Console();

    public double calculateMortgage() {
        return console.principal
                * console.monthlyInterest * Math.pow(1 + console.monthlyInterest, console.numberOfPayments)
                / (Math.pow(1 + console.monthlyInterest, console.numberOfPayments) - 1);
    }

    private double calculateBalance(short numberOfPaymentsMade) {
        return console.principal
                * (Math.pow(1 + console.monthlyInterest, console.numberOfPayments)
                - Math.pow(1 + console.monthlyInterest, numberOfPaymentsMade))
                / (Math.pow(1 + console.monthlyInterest, console.numberOfPayments) - 1);
    }

    public double[] getRemainingBalances() {
        var balances = new double[console.numberOfPayments];
        for (short month = 1; month <= balances.length; month++)
            balances[month -1] = calculateBalance(month);
        return balances;
    }
}

As you can see, there’re lots of console. and the variable I want to use from the Console class. Is there a way to cut down on those (other than just setting 3 fields specifying each variable to a new name, that’s not what I’m looking for)?
I’m looking for a clean solution which doesn’t need to use 3 fields in the CalculateMortgage class.

Edit: any other observation to clean the code/improve it or whatever is useful as well!

We can probably resolve this over in your original post (Any flaws on my Mortgage Calculator?), but basically it looks like your Console class is not the right place to be storing those values.

1 Like