Home > Back-end >  How to refactor this enum into OOP?
How to refactor this enum into OOP?

Time:08-21

I'm studying for a test at the moment and I'm struggling with this question

enter image description here

The questions follows:

A) Suppose one would like to add an object BY_TWELVE to the enumeration without change the structure of it. What would that mean in the code above? Tell clearly or write the new version of the code!

B) What is called the refactoring that would be needed for the enumeration to follow basic OOP principles?

C) Refactor the code so that the addition of the BY_TWELVE object only needs to change one single line of code in the class afterwards. You get the best solution if the apply() method does not is static. Keep in mind that the existing code can be improved in several ways, and that you don't need to maintain exactly the same interface as before.

On A) Ive put in a enum BY_TWELVE and also put it in as a case, so i think its that simple. On B) I think the refactoring has to be a method refectoring, not 100% sure. What I'm struggling with is C), I've been googling and thinking of solutions for hours now but I'm stuck. So would be very gratefull if anyone could push me to right path.

CodePudding user response:

I would change the method this way:

public Integer apply (Integer input) {
    return input*step;
}

And it can be called:

BY_TWO.apply(<an integer>)

Full code:

public enum Increment {

    BY_ONE(1), BY_TWO(2), BY_FIVE(5);

    private Integer step;

    private Increment(Integer step) {
        this.step = step;
    }
    
    public Integer apply (Integer input) {
        return input*step;
    }
}
  • Related