/** Demonstrate poor and good ways to map a loop index to a desired value. */ public class CalcDirection { /** A bonehead solution */ public void bigMethod() { for(int dir=0; dir < 4; dir++) { switch (dir) { case 0: System.out.println("Some big calculation using 0"); break; case 1: System.out.println("Some big calculation using 90"); break; case 2: System.out.println("Some big calculation using 180"); break; case 3: System.out.println("Some big calculation using 270"); break; } } } /** A poor solution - redundant code */ public void smallMethod() { System.out.println("Some big calculation using 0"); System.out.println("Some big calculation using 90"); System.out.println("Some big calculation using 180"); System.out.println("Some big calculation using 270"); } //------------------------------------------------------------------------ public void useLookupTable(int direction) { final int[] degrees = {0,90,180,270}; System.out.println("Some big calculation using " + degrees[direction]); } /** An acceptable solution - use a lookup table */ public void noRedundantCode1() { // First Approach for(int dir=0; dir < 4; dir++) { useLookupTable(dir); } } //------------------------------------------------------------------------ /** A good solution - uses an enumeration type */ private enum Directions {north, east, south, west}; public void useEnum() { // Third Approach - avoid magic numbers for(Directions dir : Directions.values()) { useLookupTable(dir.ordinal()); } } //------------------------------------------------------------------------ /** A clever good solution - use a formula to map direction to degrees */ public void doCalculation(int direction) { int degrees = direction * 90; System.out.println("Some big calculation using " + degrees); } public void noRedundantCode2() { // Second Approach - smart! for(int dir=0; dir < 4; dir++) { doCalculation(dir); } } //------------------------------------------------------------------------ public static void main(String[] args) { new CalcDirection().bigMethod(); new CalcDirection().smallMethod(); new CalcDirection().noRedundantCode1(); new CalcDirection().noRedundantCode2(); new CalcDirection().useEnum(); } }