Refactoring for OOP - Choosing what to refactor

I’m about 50% of the way through Java Part 2. We’ve just refactored the Financial Calculator script from procedural to OOP. Through the process we eliminated a lot of duplication and simplified the code in many places. However, there is one piece of duplication that still remains, and I’m unsure why it was not also modified. I think I know how I could remove the duplication, by creating class variables and taking the declarations out of the methods, but I don’t know if I should do this. And if not, why not?

Really, I’m just trying to understand the rationale for when/why you would create a class variable versus keeping it as a method variable.

The section specifically that I’m inquiring about is in the MortgageCalculator class. The following variables are declared in both the calculateBalance() and calculateMortgage() methods.
float monthlyInterest = getMonthlyInterest();
float numberOfPayments = getNumberOfPayments();

This question is a bit more theoretical in nature, but I’m hoping to gain some insight from the community.

I think it probably depends on the application. In my own implementation, I only stored the monthly numbers (like number of monthly payments and monthly interest). How you do things is dependent on what your code needs to do. How much refactoring to do is also a bit of a personal choice. In general you are trying to make the code as clean as possible but do not let the perfect be the enemy of the good. In the real world there is such a thing as “good enough” which is significantly less than perfect.

2 Likes