Created
March 12, 2015 06:39
-
-
Save jamesrcounts/f78de2f7ea2d02eb3350 to your computer and use it in GitHub Desktop.
IF to Hash refactoring
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//1) Starting code... | |
Color color; | |
if (branchLength == 10) { | |
color = PenColors.Greens.Lime; | |
} else if (branchLength == 20) { | |
// ... | |
} else if (branchLength == 30) { | |
// ... | |
} | |
//2) 1st Refactoring introduces the map, and replaces the first if statement. | |
// Add the map and the first case to the map | |
HashMap<Integer, Color> colors = new HashMap<Integer, Color>(); | |
colors.put(10, PenColors.Greens.Lime); | |
Color color; | |
// rewrite the first branch to check the map | |
if (colors.containsKey(branchLength)) { | |
color = colors.get(branchLength); | |
} else if (branchLength == 20) { | |
// ... | |
} else if (branchLength == 30) { | |
// ... | |
} | |
//3) Refactorings 2 .. n replace the rest of the if branches. | |
// Add the map and the first case to the map | |
HashMap<Integer, Color> colors = new HashMap<Integer, Color>(); | |
colors.put(10, PenColors.Greens.Lime); | |
colors.put(20, PenColors.Greens.ForestGreen); // <-- 20 moved here | |
Color color; | |
if (colors.containsKey(branchLength)) { | |
color = colors.get(branchLength); | |
} else if (branchLength == 30) { // <--- 20 is gone, starts at 30 now | |
// ... | |
} | |
//Finally only the first branch of the if statement remains, and you can remove the If, leaving behind only the map. | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment