책/이펙티브 자바
-
item 30 이왕이면 제네릭 메서드로 만들어라책/이펙티브 자바 2022. 3. 22. 21:02
ITEM 30 이왕이면 제네릭 메서드로 만들어라 제네릭 메서드 제네릭 메서드 작성법은 제네릭 클래스 작성법과 비슷하다 로 타입을 사용한 메서드 public static Set union(Set s1, Set s2) { Set result = new HashSet(s1); result.addAll(s2); return result; } 위의 메서드를 안전하게 만들려면 타입을 안전하게 만들어야 한다 메서드 선언에서의 입력2개, 리턴1개 이 원소 타입을 타입 매개변수로 명시한다 메서드 내부에서 명시한 타입 매개변수만 사용한다 타입 매개변수 목록은 메서드의 접근제어자와 리턴 타입 사이에 온다 타입 매개변수 목록 : 리턴 타입 : Set public static Set union(Set s1, Set s2) { ..
-
item 29 이왕이면 제네릭 타입으로 만들라책/이펙티브 자바 2022. 3. 21. 14:13
ITEM 29 이왕이면 제네릭 타입으로 만들라 작성하는 코드 내에 Object로 받는 부분이 있다면 제네릭으로 변경이 가능한지 고려해보자 클라이언트에서 직접 형변환을 해주는 타입보다 제네릭 타입이 더 안전하고 사용하기에 편리하다 새로운 타입을 설계 하는 경우에는 형변환을 하지 않고도 사용이 가능하도록 설계하자 형변환을 하지 않고 사용이 가능하게 하려면 제네릭을 사용해야 하는 경우가 많다 작성하는 코드 뿐만 아니라 기존에 존재하던 코드에서도 제네릭 타입으로 변경이 가능한 코드가 있다면 변경하자 제네릭 타입을 사용하면 기존 클라이언트 코드는 아무 영향을 받지 않지만 새로운 사용자는 훨씬 더 편리하게 사용 할 것이다 제네릭 타입을 사용하므로써 확장성 및 유연성이 증대된다 컴파일 단계에서 오류 검증이 가능해져 ..
-
item 28 배열보다는 리스트를 사용하라책/이펙티브 자바 2022. 3. 19. 22:21
ITEM 28 배열보다는 리스트를 사용하라 배열과 제네릭 타입의 차이 배열은 공변이다 함께 변한다는 뜻 sub가 super의 하위 타입이라면 배열sub[]는 배열 super[]의 하위 타입이 된다 제네릭은 불공변이다 서로 다른 타입 type1 , type2 가 있다면 List은 List의 하위 타입도 아니고 상위 타입도 아니다 문제가 있는건 제네릭이 아닌 배열이다(제네릭은 컴파일 단계에서 문제를 알 수 있지만 배열은 런타임 단계에서 오류를 발생한다) 배열은 실체화(reify) 된다 런타임에도 자신이 담기로 한 원소의 타입을 인지하며 확인한다 제네릭은 타입 정보가 런타임에는 소거된다 원소 타입을 컴파일타임에만 검사하고 런타임시기에는 알 수 없다 소거는 제네릭이 지원되기 전의 레거시 코드와 제네릭 타입의 호..
-
item 27 비검사 경고를 제거하라책/이펙티브 자바 2022. 3. 17. 23:52
ITEM 27 비검사 경고를 제거하라 제네릭을 사용하기 시작하면 수많은 컴파일러 경고를 보게된다 비검사 형변환 경고 비검사 메서드 호출 경고 비검사 매개변수화 가변인수 타입 경고 비검사 변환 경고 제네릭에 익숙해지면 보게되는 경고의 개수는 줄어들겠지만 새로 만든 코드가 한번에 컴파일 될거라고 기대하지는 말자 할 수 있는 한 모든 비검사 경고는 제거하고 비검사 경고는 중요하니 무시하지 말자 비검사 경고를 모두 제거하면 해당 코드는 타입 안정성이 보장된다 런타임에 ClassCastException이 발생할 일이 없으며 작성자의 의도대로 동작한다 모든 비검사 경고는 런타임에 ClassCastException을 일으킬 수 있는 잠재적 가능성을 뜻하니 최선을 다해 제거해라 경고를 없앨 방법을 먼저 찾아보고 만약 ..
-
item 26 로 타입은 사용하지 말라책/이펙티브 자바 2022. 3. 16. 22:02
ITEM 26 로 타입은 사용하지 말라 제네릭 타입 제네릭 클래스와 제네릭 인터페이스를 통틀어 제네릭 타입이라 부른다 제네릭 클래스, 제네릭 인터페이스 : 클래스와 인터페이스 선언에 타입 매개변수가 사용된것List은 원소 타입이 String인 리스트를 뜻하는 매개변수화 타입이다 각각의 제네릭 타입은 일련의 매개변수화 타입을 정의한다 먼저 클래스 이름이 나오고 꺾쇠괄호 안에 실제 타입 매개변수들을 나열한다 String이 정규타입 매개변수 E에 해당하는 실제 타입 매개변수다 제네릭을 사용하면 컴파일러가 원소를 꺼내는 모든 곳에 보이지 않는 형변환을 추가하여 절대 실패하지 않음을 보장한다 로타입 제네릭 타입을 하나 정의하면 그에 딸린 로타입도 함께 정의된다 로타입 : 제네릭 타입에서 타입 매개변수를 전혀 사용..
-
item 25 톱 레벨 클래스는 한 파일에 하나만 담으라책/이펙티브 자바 2022. 3. 15. 22:46
ITEM 25 톱 레벨 클래스는 한 파일에 하나만 담으라 소스 파일 하나에 톱레벨 클래스를 많이 선언해도 컴파일에 문제는 없지만 아무 의미가 없고 위험만 증가한다 한 클래스를 여러가지로 정의가 가능해지고 어느게 사용되는지는 컴파일 순서에 따라 달라지기 때문이다 public class Main { public static void main(String[] args) { System.out.println(Utensil.NAME + Dessert.NAME); } } Utensil.java class Utensil { static final String NAME = "pan"; } class Dessert { static final String NAME = "cake"; } Dessert.java class U..
-
item 24 멤버 클래스는 되도록 static으로 만들라책/이펙티브 자바 2022. 3. 14. 20:21
ITEM 24 멤버 클래스는 되도록 static으로 만들라 중첩 클래스 다른 클래스 안에 정의된 클래스이다 자신을 감싼 바깥 클래스에서만 사용 되어야 한다 다르게 사용하는 경우는 톱레벨 클래스로 만들어야 한다 중첩 클래스의 종류는 정적 멤버 클래스, 멤버 클래스(비정적 클래스), 익명 클래스, 지역 클래스가 있다 첫 번째를 제외한 나머지 클래스는 내부 클래스다 정적 멤버 클래스 다른 클래스 안에 선언된다 바깥 클래스의 private 멤버에도 접근할 수 있다 나머지는 일반 클래스와 같다 정적 멤버 클래스는 다른 정적 멤버와 똑같은 접근 규칙을 적용받는다 private로 선언하면 바깥 클래스에서만 접근 가능하다 정적 멤버 클래스는 바깥 클래스와 함께 사용되는 경우 public 도우미로 유용하게 쓰인다 정적 ..
-
item 23 태그 달린 클래스보다는 클래스 계층구조를 활용하라책/이펙티브 자바 2022. 3. 14. 19:57
ITEM 23 태그 달린 클래스보다는 클래스 계층구조를 활용하라 태그 달린 클래스 두 가지 이상의 의미를 표현할 수 있으며 현재 표현하는 의미를 태그 값으로 알려주는 클래스 태그 달린 클래스의 단점 열거 타입의 선언, 태그 필드, switch 문 등 쓸데없는 코드가 많다 여러 구현이 한 클래스에 들어있어 가독성이 안좋다 다른 의미를 위한 코드가 같이 있으니 메모리 사용량이 많다 필드들을 final로 선언하려면 해당 의미에 쓰이지 않는 필드까지 생성자에서 초기화 해야한다 태그 달린 클래스는 장황하며 오류가 나기 쉬우며 비효율적이다 클래스 계층구조 타입 하나로 다양한 의미의 객체를 표현 가능한 좋은 수단이다 태그 달린 클래스는 클래스 계층구조를 어설프게 흉내낸 아류일 뿐이다 태그 달린 클래스를 클래스 계층구..
-
item 22 인터페이스는 타입을 정의하는 용도로만 사용하라책/이펙티브 자바 2022. 3. 10. 23:45
ITEM 22 인터페이스는 타입을 정의하는 용도로만 사용하라 인터페이스는 자신을 구현한 클래스의 인스턴스를 참조할 수 있는 타입 역할을 한다 클래스가 어떤 인터페이스를 구현했는가에 따라 클라이언트에서 해당 클래스의 인스턴스로 무엇을 할 수 있는지 파악이 가능하다 인터페이스는 이 용도로만 써야한다 상수 인터페이스처럼 상수 공개용 수단으로 사용하면 안된다 안티패턴 상수 인터페이스 메서드 없이 상수(static final) 필드만 있는 인터페이스 정규화된 이름을 쓰는걸 피하려고 이런 인터페이스를 구현하는 클래스가 생기게된다 상수 인터페이스는 안티패턴으로 인터페이스를 잘 못 활용한 예이다 클래스 내부에서 사용하는 상수는 외부 인터페이스가 아니라 내부 구현인데 상수 인터페이스를 구현하면 내부 구현을 외부로 노출하..
-
item 21 인터페이스는 구현하는 쪽을 생각해 설계하라책/이펙티브 자바 2022. 3. 9. 23:01
ITEM 21 인터페이스는 구현하는 쪽을 생각해 설계하라 자바 8이전에는 기존 구현체를 깨뜨리지 않고 인터페이스에 새로운 메서드를 추가하는 방법이 없었다 자바 8부터 디폴트 메서드를 통해 기존 인터페이스에 새로운 메서드를 추가할 수 있게 되었다 디폴트 메서드를 사용하면 인터페이스를 구현한 모든 구현체에서 디폴트 메서드를 재정의 하지 않아도 디폴트 메서드를 사용 가능하다 디폴트 메서드가 생겨난 덕분에 하위 호환성이 좋아졌지만 자바 8 이전에 작성된 코드들은 인터페이스에 새로운 메서드가 추가되는 일은 없을거라고 가정하고 짠 것이니 항상 주의해야 한다 디폴트 메서드가 하위 호환성이 좋지만 모든 경우에 매끄럽게 연결되지 않을수 있다 생각할 수 있는 모든 상황에서 불변식을 해치지 않는 디폴트 메서드를 작성하기는 ..