Avoid Repeated Code

Repetition of code that is almost the same is an indication that your program should be restructured: have only a single copy of the code, use tables for the differences.[Sadly, the examples of bad code here are from Sun's Java Tutorial web site.]


if (month == 1) {
    System.out.println("January");
} else if (month == 2) {
    System.out.println("February");
}
... 

switch (month) {
  case 1:  System.out.println("January"); break;
  case 2:  System.out.println("February"); break;
  case 3:  System.out.println("March"); break;
  ...
  default: System.out.println("Invalid month.");break;
  }

Better:


System.out.println(months[month]);

Contents    Page-10    Prev    Next    Page+10    Index