Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to refactor this enum into OOP?

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

enter image description here

The questions follows:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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;
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading