2.코드스타일 레벨업

2.1 매직넘버를 상수로 대체

  • 무의미한 내용 대신 의미 있는 상수로 대체

if (speedPreset == 2){
// ..
} else if(speedPreset == 1){
// ..
} else if(speedPreset == 0) {
// ..
}
private static final int STOP_PRESET = 0;
private static final int PLANETARY_SPEED_PRESET = 1;
private static final int CRUISE_SPEED_PRESET = 2;

2.2 정수 상수 대신 열거형

  • 상수 -> enum 대체 검토

enum SpeedPreset {
  STOP(0), PLANETRAY(1), CRUISE(2);
}

2.3 For루프 대신 Foreach

  • 람다 고려

2.4 순회하며 컬렉션 수정하지 않기

  • 사이즈 변경, 값변경 -> 예상치 못한 결과가 나올 수 있음

  • 컬렉션 순회 동안 그 컬렉션 수정 -> ConcurrentModificationException 예외 발생

class Inventory{
  private List<Supply> supplies = new ArrayList<>();
  
  void disposeCOntaminatedSupplies() {
    for (Supply supply : supplies) {
      if (supply.isContaminated()){
        supplies.remove(supply); // 금지 !! 이러면 망함
      }
    }
  }
}
  • 먼저 순회 -> 순회 후 수정(삭제)

// Iterator를 활용하면 괜찮음
  void disposeCOntaminatedSupplies() {
    Iterator<Supply> iter = supplies.iterator();
    while (iter.hasNext()) {
      if (iter.next().isContaminated()){
        iterator.remove(); 
      }
    }
  }

Last updated