Skip to content
Advertisement

How do I refactor multiple if-else statements in Java?

How do I refactor all this code that seems repetitive and too long, is there a way to make it shorter?

JavaScript

I have tried using the Switch statement but that does not work in this circumstance.

the “typeOfData” variable holds a String that is used to match relevant lines.

Advertisement

Answer

Simplify

You can extract the common lines, before or after the ifs

JavaScript

Improve

You could imagine the constructors to take the Scanner as parameter like

JavaScript

Then the ifs becomes

JavaScript

Or a switch

JavaScript
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement