Skip to content

Instantly share code, notes, and snippets.

@jamesrcounts
Created March 12, 2015 06:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jamesrcounts/f78de2f7ea2d02eb3350 to your computer and use it in GitHub Desktop.
Save jamesrcounts/f78de2f7ea2d02eb3350 to your computer and use it in GitHub Desktop.
IF to Hash refactoring
//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