분류 전체보기
-
item 39 명명 패턴보다 애너테이션을 사용하라책/이펙티브 자바 2022. 4. 6. 09:43
ITEM 39 명명 패턴보다 애너테이션을 사용하라 전통적으로 도구나 프레임워크가 특별히 다뤄야 할 프로그램 요소에는 딱 구분되는 명명 패턴을 적용했다 명명 패턴은 효과적인 방법이지만 단점도 크다 오타가 나면 안된다 jUnit 버전 3까지 테스트 메서드 이름을 test로 시작하게 했는데 test가 아닌 tset이런식으로 오타나 나게되면 해당 메서드를 무시하고 지나치게 된다 올바른 프로그램 요소에서만 사용되리라 보증할 방법이 없다는 것이다 클래스 이름을 TestSafetyMechanisms로 지어 jUnit에 던졌다고 가정했을때 jUnit은 클래스 이름은 신경을 쓰지 않는다 프로그램 요소를 매개변수로 전달할 마땅한 방법이 없다 특정 예외를 던져야 성공하는 테스트인경우 기대하는 예외 타입을 테스트에 매개변수로..
-
item 38 확장 할 수 있는 열거타입이 있으면 인터페이스를 사용하라책/이펙티브 자바 2022. 4. 6. 09:42
ITEM 38 확장 할 수 있는 열거타입이 있으면 인터페이스를 사용하라 열거 타입은 거의 모든 상황에서 타입 안전 열거 패턴(typesafe enum pattern)보다 우수하다 한가지 예외적인 경우는 타입 안전 열거 패턴은 확장할 수 있지만 열거 타입은 그럴 수 없다 타입 안전 열거 패턴은 열거한 값들을 그대로 가져온 다음 값을 더 추가하여 다른 목적으로 쓸 수 있지만 열거 타입은 그렇게 할 수 없다 실수로 이렇게 설계한 것이 아니며 대부분의 상황에서 열거 타입을 확장하는건 좋지 않다 확장한 타입의 원소는 기반 타입의 원소로 취급하지만 그 반대는 성립하지 않는다면 이상하다 또한 기반 타입과 확장된 타입들의 원소 모두를 순회하는 방법도 마땅하지 않다 확장성을 높이려면 고려 할 요소가 늘어나 설계와 구현이..
-
item 37 oridinal 인덱싱 대신 EnumMap을 사용하라책/이펙티브 자바 2022. 4. 6. 09:42
ITEM 37 oridinal 인덱싱 대신 EnumMap을 사용하라 배열이나 리스트에서 원소를 꺼낼 때 ordinal 메서드로 인덱스를 얻는 코드가 있다 식물을 간단하게 나타낸 클래스 class Plant { enum LifeCycle { ANNUAL, PERENNIAL, BIENNIAL } final String name; final LifeCycle lifeCycle; Plant(String name, LifeCycle lifeCycle) { this.name = name; this.lifeCycle = lifeCycle; } @Override public String toString() { return name; } } 정원에 심은 식물들을 배열 하나로 관리하고 이들을 생애주기별로 묶어보자 생애주기..
-
item 35 ordinal 메서드 대신 인스턴스 필드를 사용하라책/이펙티브 자바 2022. 3. 29. 17:27
ITEM 35 ordinal 메서드 대신 인스턴스 필드를 사용하라 대부분의 열거 타입 상수는 자연스럽게 하나의 정숫값에 대응된다 열거 타입은 해당 상수가 그 열거 타입에서 몇 번째 위치인지를 반환하는 ordinal 이라는 메서드를 제공한다 이렇게 제공을 하니까 열거 타입 상수와 연결된 정숫값이 필요하면 ordinal 메서드를 쓰고 싶어진다 합주단의 종류를 연주자가 1명인 솔로부터 10명인 디텍트 까지 정의한 열거타입 ordinal을 잘못 사용한 예제 public enum Ensemble { SOLO, DUET, TRIO, QUARTET, QUINTET, SEXTET, SEPTET, OCTET, NONET, DECTET public int numberOfMusicians() { return ordinal(..
-
item 34 int 상수 대신 열거 타입을 사용하라책/이펙티브 자바 2022. 3. 28. 13:35
ITEM 34 int 상수 대신 열거 타입을 사용하라 열거타입 일정 개수의 상수 값을 정의하고 그 외의 값은 허용하지 않는 타입 정수 열거 패턴 자바에서 열거 타입을 지원하기 전에 사용하던 패턴으로 정수 상수를 한 묶음 선언해서 사용하는 단점이 많은 패턴이다정수 열거 패턴 public static final int APPLE_FUJI = 0; public static final int APPLE_PIPPIN = 1; public static final int APPLE_GRANNY_SMITH = 2; public static final int ORANGE_NAVEL = 0; public static final int ORANGE_TEMPLE = 1; public static final int ORANGE..
-
문자열 계산기 정리책/자바 웹 프로그래밍 next step 2022. 3. 27. 22:54
정리 앞에서 문자열 계산기의 개발 과정은 구현 > 테스트를 통한 결과 확인 > 리팩토링으로 진행되었다 이 과정 중 보통 개발자들은 리팩토링을 소홀하게 한다 깔끔하고 읽기 좋은 코드를 위해서는 리팩토링 역량이 중요하기 때문에 꾸준히 연습하자 추후 개발을 진행하는 경우에도 아래의 3가지 원칙을 지키도록 노력하자 메서드가 한 가지 책임만을 가지도록 한다 인덴트(indent , 들여쓰기) 깊이를 1단계로 유지한다 while 문과 if문을 사용할 경우 인덴트 깊이가 1씩 증가한다 아래 예제는 인덴트가 2다 while (true) { if (true) { } } else를 사용하지 마라 리팩토링을 진행하면서 어디를 고쳐야 될지 모르겠다면 위의 3가지 원칙을 생각해보자 앞에서 리팩토링을 극단적으로 진행이 가능했던 이..
-
chapter02 동작 파라미터화 코드 전달하기책/모던 자바 인 액션 2022. 3. 26. 23:50
chapter02 동작 파라미터화 코드 전달하기 동작 파라미터화 동작 파라미터화란 아직은 어떻게 실행할 것인지 결정하지 않은 코드 블록을 의미한다 이 코드 블록은 나중에 프로그램에서 호출한다(코드 블록의 실행은 나중이다) 나중에 실행될 메서드의 인수로 코드 블록을 전달 할 수 있다 코드 블록에 따라 메서드의 동작이 파라미터화 된다 동작 파라미터화를 이용하면 자주 변하는 요구사항에 효과적으로 대응 할 수 있다 변화하는 요구사항에 대응하기 1. 녹색 사과 필터링 enum Color { RED , GREEN } public static List filterGreenApples(List inventory) { List result = new ArrayList(); for (Apple apple : invento..
-
item 33 타입 안전 이종 컨테이너를 고려하라책/이펙티브 자바 2022. 3. 25. 23:17
ITEM 33 타입 안전 이종 컨테이너를 고려하라 타입 안전 이종 컨테이너 패턴(type safe heterogeneous container pattern) 컨테이너 대신 키를 매개변수화 하고 컨테이너에 값을 넣거나 뺄때 매개변수화한 키를 함께 제공하여 제네릭 타입 시스템이 값의 타입이 키와 같음을 보장해주는것 //Favorites api public class Favorites { public void putFavorite(Class type, T instance); public T getFavorite(Class type); } //Favorites의 구현 public class Favorites { private Map
-
item 32 제네릭과 가변인수를 함께 쓸 때는 신중하라책/이펙티브 자바 2022. 3. 24. 17:34
ITEM 32 제네릭과 가변인수를 함께 쓸 때는 신중하라 가변인수 가변인수를 사용하면 메서드에 넘기는 인수의 개수를 클라이언트가 조절 가능 가변인수 메서드를 호출하면 가변인수를 담기 위한 배열이 하나 생긴다 이 배열이 내부로 감춰 지는게 아니라 클라이언트에 노출되는 문제가 있다 따라서 varargs 매개변수에 제네릭이나 매개변수화 타입이 포함되면 알기 어려운 경고가 발생한다 거의 대부분의 제네릭과 매개변수화 타입은 실체화 되지 않는다 실체화 불가 타입은 컴파일 타임보다 런타임시에 타입에 대한 정보를 적게 담고 있다 메서드를 선언할때 실체화 불가 티입으로 varargs 매개변수를 선언하면 경고가 출력된다 가변인수 메서드 호출시에도 varargs 매개변수가 실체화 불가 타입이면 아래 경고가 나타난다 warn..