책/이펙티브 자바
-
item 50 적시에 방어적 복사본을 만들라책/이펙티브 자바 2022. 4. 13. 16:35
ITEM 50 적시에 방어적 복사본을 만들라 자바는 안전한 언어이며 이게 자바를 쓰는 즐거움 중 하나다 네이티브 메서드를 사용하지 않아 C,C++ 같은 안전하지 않은 언어에서 보이는 버퍼 오버런, 배열 오버런, 와일드 포인터 같은 메모리 충돌 오류에서 안전하다 자바로 작성한 클래스는 시스템의 다른 부분에서 무슨 짓을 하든 그 불변식이 지켜진다 메모리 전체를 하나의 배열로 다루는 언어에서는 누릴 수 없는 강점이다 하지만 아무리 자바라도 다른 클래스로부터의 침범을 아무런 노력 없이 다 막을 수 없다 클라이언트가 여러분의 불변식을 깨뜨리려 혈안이 되어 있다고 가정하고 방어적으로 프로그래밍해야 한다 실제로도 악의적인 의도를 가진 사람들이 시스템의 보안을 뚫으려는 시도가 늘고 있다 평범한 개발자도 순전히 실수로 ..
-
item 49 매개변수가 유효한지 검사하라책/이펙티브 자바 2022. 4. 13. 14:42
ITEM 49 매개변수가 유효한지 검사하라 메서드와 생성자 대부분은 입력 매개변수의 값이 특정 조건을 만족하기를 바란다 한 예로 인덱스 값은 음수면 안되고 객체 참조는 null이 아닌것 이러한 제약조건은 반드시 문서화 시켜야되며 메서드 몸체가 시작되기 전에 검사해야 한다 이건 오류는 가능한 한 빨리 (발생한 곳에서) 잡아야 한다 는 일반 원칙의 한 사례이기도 하다 오류를 발생한 즉시 잡지 못하면 해당 요류를 감지하기 어려워지고 감지하더라도 오류의 발생 지점을 찾기 어려워진다 메서드 몸체가 실행되기 전에 매개변수를 확인한다면 잘못된 값이 넘어왔을때 즉각적이고 깔끔한 방식으로 예외를 던질 수 있다 매개변수 검사를 제대로 하지 못하면 몇 가지 문제가 생길 수 있다 메서드가 수행되는 중간에 모호한 예외를 던지며..
-
item 48 스트림 병렬화는 주의해서 적용하라책/이펙티브 자바 2022. 4. 13. 13:27
ITEM 48 스트림 병렬화는 주의해서 적용하라 주류 언어 중, 동시성 프로그래밍 측면에서 자바는 항상 앞서갔다 처음 릴리즈된 1996년부터 스레드, 동기화, wait/notify를 지원했다 자바 5부터는 동시성 컬렉션인 java.util.concurrent 라이브러리와 실행자(Executor) 프레임워크를 지원했다 자바 7부터는 고성능 병렬 분해(parallel decom-position)프레임워크인 포크-조인(fork-join) 패키지를 추가했다 자바 8부터는 parallel 메서드만 한 번 호출하면 파이프라인을 병렬 실행할 수 있는 스트림을 지원했다 자바로 동시성 프로그램을 작성하는게 계속 쉬워지고 있지만 이를 올바르고 빠르게 작성하는건 여전히 어렵다 동시성 프로그래밍을 할 때는 안전성(safety..
-
item 47 반환 타입으로는 스트림보다 컬렉션이 낫다책/이펙티브 자바 2022. 4. 12. 17:35
ITEM 47 반환 타입으로는 스트림보다 컬렉션이 낫다 원소 시퀀스(일련의 원소)를 반환하는 메서드는 수없이 많으며 자바 7까지는 이런 메서드의 반환 타입을 Collection, SEt, List 같은 컬렉션 인터페이스나 Iterable이나 배열을 사용했다 이 중에서 가장 적합한 타입을 선택하는게 어렵지 않았다 컬렉션 인터페이스 : 기본으로 사용 Iterable 인터페이스 : for-each 문에서만 쓰이거나 반환된 원소 시퀀스가(주로 contains(Object) 같은) 일부 Collection 메서드를 구현할 수 없을때 배열 : 반환 원소들이 기본 타입이거나 성능에 민감한 상황 하지만 자바 8이 스트림이라는 개념을 들고 오면서 선택이 복잡해졌다 스트림은 반복을 지원하지 않아서 스트림과 반복을 조합해야..
-
item 46 스트림에서는 부작용 없는 함수를 사용하라책/이펙티브 자바 2022. 4. 12. 16:56
ITEM 46 스트림에서는 부작용 없는 함수를 사용하라 스트림 패러다임의 핵심은 계산을 일련의 변환으로 재구성 하는것 각 변환 단계는 가능한 이전 단계의 결과를 받아 처리하는 순수 함수여야 한다 순수 함수 : 오직 입력만이 결과에 영향을 주는 함수 다른 가변 상태를 참조하지 않고, 함수 스스로도 다른 상태를 변경하지 않고 함수 스스로도 다른 상태를 변경하지 않음 따라서 중간 단계든 종단 단계든 스트림 연산에 건네는 함수 객체는 모두 부작용이 없어야 한다 스트림 패러다임을 이해하지 못한 api 사용법 텍스트 파일에서 단어별 수를 세어 빈도표로 만든다 Map freq = new HashMap(); try (Stream words = new Scanner(file).tokens()) { words.forEac..
-
item 45 스트림은 주의해서 사용하라책/이펙티브 자바 2022. 4. 11. 17:06
ITEM 45 스트림은 주의해서 사용하라 스트림 API는 다량의 데이터 처리 작업(순차적이든 병렬적이든)을 위해 java8에 추가됐다 스트림 API가 제공하는 추상 개념 중 핵심은 두가지다 스트림(stream)은 데이터 원소의 유한 혹은 무한 시퀀스(sequence)를 뜻한다 스트림 파이프라인(stream pipeline)은 이 원소들로 수행하는 연산 단계를 표현하는 개념이다 스트림의 원소들은 어디로부터든 올 수 있으며 대표적으로 컬렉션, 배열, 파일, 정규표현식 패턴 매처(matcher),난수 생성기, 혹은 다른 스트림이 있다 스트림 안의 데이터 원소들은 객체 참조나 기본 타입 값이다 기본 타입 값으로는 int, long, double 세가지를 지원한다 스트림 파이프라인은 소스 스트림에서 시작해 종단 ..
-
item 44 표준 함수형 인터페이스를 사용하라책/이펙티브 자바 2022. 4. 11. 16:17
ITEM 44 표준 함수형 인터페이스를 사용하라 자바가 람다를 지원하며 API를 작성하는 모범 사례도 크게 바뀌었다 한 예로 템플릿 메서드 패턴의 매력이 크게 줄었다 상위 클래스의 기본 메서드를 재정의해 원하는 동작을 구현하는 패턴 이를 대체하는 현대적인 해법은 아래와 같다 같은 효과의 함수 객체를 받는 정적 팩터리나 생성자를 제공하는 것 이 내용을 일반화해서 말하면 함수 객체를 매개변수로 받는 생성자와 메서드를 더 많이 만들어야한다 이때 함수형 매개변수 타입을 올바르게 선언해야 한다 LinkedHashMap을 예로 들어보자 LinkedHashMap의 protected 메서드인 removeEldestEntry를 재정의하면 캐시로 사용 가능하다 맵에 새로운 키를 추가하는 put 메서드는 이 메서드를 호출하..
-
item 43 람다보다는 메서드 참조를 사용하라책/이펙티브 자바 2022. 4. 11. 16:17
ITEM 43 람다보다는 메서드 참조를 사용하라 메서드 참조 람다가 익명 클래스보다 좋은점 중 가장 큰 특징은 간결함인데 함수 객체를 람다보다도 간결하게 만드는 방법이다 임의의 키와 Integer 값의 매핑을 관리하는 프로그램의 일부 map.merge(key, 1, (count, incr) -> count + incr);//키가 맵안에 없으면 키와 숫자 1이 맵핑, 있으면 기존 매핑 값 증가 값이 키의 인스턴스 개수로 해석된다면 멀티셋을 구현한게 된다 위 코드는 깔끔하게 보이지만 매개변수 count와 incr이 하는일 없이 공간을 차지한다 위 람다는 두 인수의 합을 단순히 반환할 뿐인데 java8의 Integer 등 기본타입의 박싱 타입은 같은 기능을 하는 sum 메서드를 제공하기 때문에 아래와 같이 코..
-
item 42 익명 클래스보다는 람다를 사용하라책/이펙티브 자바 2022. 4. 6. 17:17
ITEM 42 익명 클래스보다는 람다를 사용하라 예전 자바에서 함수 타입을 표현하는 경우 추상 메서드를 하나만 담은 인터페이스(드물게는 추상클래스)를 사용했다 이런 인터페이스를 함수객체(function object)라고 하여 특정 함수나 동작을 나타내는 경우 사용 jdk 1.1 등장 이후 함수 객체를 만드는 주요 수단은 익명클래스가 되었다 문자열을 길이 순으로 정렬하는 코드(정렬을 위한 비교 함수로 익명 클래스를 사용한다) 익명 클래스의 인스턴스를 함수 객체로 사용하는 방법 (옛날방법) Collections.sort(words, new Comparator() { public int compare(String s1, String s2) { return Integer.compare(s1.length(), s..
-
item 41 정의하려는 것이 타입이라면 마커 인터페이스를 사용하라책/이펙티브 자바 2022. 4. 6. 10:38
ITEM 41 정의하려는 것이 타입이라면 마커 인터페이스를 사용하라 마커 인터페이스 아무 메서드도 담고 있지 않으며 자기 자신을 구현하는 클래스가 특정 속성을 가짐을 표시해주는 인터페이스 Serializable 인터페이스가 좋은 예다 Serializable은 자신을 구현한 클래스의 인스턴스는 ObjectOutputStream을 통해 write를 사용 가능하다고 알려준다(직렬화 가능) 마커 애너테이션이 등장하면서 마커 인터페이스는 구식이 되었다는 말이 있지만 사실이 아니다 마커 인터페이스는 마커애너테이션보다 두 가지 측면에서 좋다 마커 인터페이스는 이를 구현한 클래스의 인스턴스들을 구분하는 타입으로 쓸 수 있으나 마커 애너테이션은 그렇지 않다 마커 인터페이스는 어엿한 타입이기 때문에 마커 애너테이션을 사용..