조슈아 블로크
-
이펙티브 자바 : Checked Exception vs. UncheckedException책책책 책을 읽읍시다/프로그래밍 2023. 7. 21. 21:33
자바는 문제 상황을 알리는 타입(throwable)으로 검사 예외(Checked Exception), 런타임 예외(UncheckedException), 에러, 이렇게 세 가지를 제공하는데, 언제 무엇을 사용해야 하는지 헷갈려 하는 프로그래머들이 종종 있다. 언제나 100% 명확한 건 아니지만 이럴 때 참고하면 좋은 멋진 지침들이 있다. 호출하는 쪽에서 복구하리라 여겨지는 상황이라면 검사 예외를 사용하라. 검사와 비검사 예외를 구분하는 기본 규칙이다. 검사 예외를 던지면 호출자가 그 예외를 catch로 잡아 처리하거나 더 바깥으로 전파하도록 강제하게 된다. 따라서 메서드 선언에 포함된 검사 예외 각각은 그 메서드를 호출했을 때 발생할 수 있는 유력한 결과임을 API 사용자에게 알려주는 것이다. 달리 말하면..
-
이펙티브 자바 : 박싱 타입 vs. 기본 타입책책책 책을 읽읍시다/프로그래밍 2023. 7. 18. 21:49
자바의 데이터 타입은 크게 두 가지로 나눌 수 있다. 바로 int, double, boolean 같은 기본 타입과 String, List 같은 참조 타입이다. 그리고 각각의 기본 타입에 대응하는 참조 타입이 하나씩 있으며, 이를 박싱된 기본 타입이라고 한다. 예컨대 int는 Integer, double은 Double, boolean은 Boolean이다. 기본 타입과 박싱된 기본 타입의 주된 차이는 크게 세 가지이다. 첫 번째, 기본 타입은 값만 가지고 있으나, 박싱된 기본 타입은 값에 더해 식별성(identity)이란 속성을 갖는다. 달리 말하면 박싱된 기본 타입의 두 인스턴스는 값이 같아도 서로 다르다고 식별될 수 있다. 두 번째, 기본 타입의 값은 언제나 유효하나, 박싱된 기본 타입은 유효하지 않은 ..
-
이펙티브 자바 : 제네릭 클래스와 제네릭 메서드책책책 책을 읽읍시다/프로그래밍 2023. 7. 7. 22:57
제네릭 클래스 아래와 같은 비(非)제네릭 스택 클래스가 있다고 해보자. public class Stack { private Object[] elements; private int size = 0; private static final int DEFAULT_INITIAL_CAPACITY = 16; public Stack() { elements = new Object[DEFAULT_INITIAL_CAPACITY]; } public void push(Object e) { ensureCapacity(); elements[size++] = e; } public Object pop() { if (size == 0) throw new EmptyStackException(); Object result = element..
-
이펙티브 자바 : 제네릭과 배열 그리고 리스트개발 나누고 더하기/자바, 스프링 2023. 7. 6. 21:37
배열과 제네릭 타입에는 중요한 차이가 두 가지 있다. 첫 번째, 배열은 공변(covariant)이다. 어려워 보이는 단어지만 뜻은 간단하다. Sub가 Super의 하위 타입이라면 배열 Sub[]는 배열 Super[]의 하위 타입이 된다(공변, 즉 함께 변한다는 뜻이다). 반면, 제네릭은 불공변(invaraint)이다. 즉, 서로 다른 타입 Type1과 Type2가 있을 때, List은 List의 하위 타입도 아니고 상위 타입도 아니다. 이것만 보면 제네릭에 문제가 있다고 생각할 수도 있지만, 사실 문제가 있는 건 배열 쪽이다. 다음은 문법상 허용되는 코드다. 하지만 다음 코드는 문법에 맞지 않는다. 어느 쪽이든 Long용 저장소에 String을 넣을 수는 없다. 다만 배열에서는 그 실수를 런타임에야 알게..
-
이펙티브 자바 : static 멤버 클래스책책책 책을 읽읍시다/프로그래밍 2023. 7. 5. 22:04
중첩 클래스(nested class)란 다른 클래스 안에 정의된 클래스를 말한다. 중첩 클래스는 자신을 감싼 바깥 클래스에서만 쓰여야 하며, 그 외의 쓰임새가 있다면 톱레벨 클래스로 만들어야 한다. 중첩 클래스의 종류는 정적 멤버 클래스, (비정적) 멤버 클래스, 익명 클래스, 지역 클래스, 이렇게 네 가지다. 이 중 첫 번째를 제외한 나머지는 내부 클래스(inner class)에 해당한다. 이번에는 각각의 중첩 클래스를 언제 그리고 왜 사용해야 하는지 알아보자. 정적 멤버 클래스 vs. 비정적 멤버 클래스 정적 멤버 클래스는 다른 클래스 안에 선언되고, 바깥 클래스의 private 멤버에도 접근할 수 있다는 점만 제외하고는 일반 클래스와 똑같다. 정적 멤버 클래스는 다른 정적 멤버와 똑같은 접근 규칙을..
-
이펙티브 자바 : toString개발 나누고 더하기/자바, 스프링 2023. 6. 30. 21:16
toString의 일반 규약에 따르면 '간결하면서 사람이 읽기 쉬운 형태의 유익한 정보'를 반환해야 한다. 아래 PhoneNumber 클래스를 예로 들면 PhoneNumber@adbbd처럼 단순히 클래스_이름@16진수로_표시한_해시코드로 반환하기 보다는 707-867-5309처럼 전화번호를 직접 알려주는 형태가 훨씬 유익하다. 또한 toSting의 규약은 "모든 하위 클래스에서 이 메서드를 재정의하라"고 한다. 새겨들어야 할 조언이다. public final class PhoneNumber { private final int areaCode, prefix, lineNum; //... } toString을 잘 구현한 클래스는 사용하기에 훨씬 즐겁고, 그 클래스를 사용한 시스템은 디버깅하기 쉽다. toStr..
-
이펙티브 자바 - equals & hashcode개발 나누고 더하기/자바, 스프링 2023. 6. 28. 22:29
equals와 hashcode는 루트 클래스인 Object에서 제공하는 오퍼레이션이고 모든 클래스들은 이 두 메서드를 재정의하지 않는 이상 Object에 정의되어 있는대로 쓰게 된다. 실무에서는 주로 식별자로 두 객체가 동일한지 비교하고 가끔 값 객체 비교에 써서 equals를 직접 구현했던 일이 적었다. HashMap, HashSet에 key로 enum이나 Integer, String같은 기본 랩퍼 클래스를 써서 hashcode는 볼일이 거의 없었지만 이 기회에 다시 한번 짚어보는것도 좋을 것 같다. equals는 일반 규약을 지켜 재정의하라 equals 메서드는 재정의하기 쉬워 보이지만 곳곳에 함정이 도사리고 있어서 자칫하면 끔찍한 결과를 초래한다. 문제를 회피하는 가장 쉬운 길은 아예 재정의하지 않..
-
이펙티브 자바 - 정적 팩터리 메서드책책책 책을 읽읍시다/프로그래밍 2023. 6. 22. 23:46
저자 : 조슈아 블로크(Joshua Bloch) 옮긴이 : 이복연 들어가며 2015년 11번가 인턴 때 중도포기, 2017년쯤 이랜드에서도 중도포기... 영화든 책이든 재미없더라도 끝까지 가고 보는 성격인데 왠지 이 책만큼은 재미있음에도 완독을 못했다. 이번에는 꼭 성공하길 바라는 마음에서 완독 전에 먼저 블로그 글을 올리는 배수진을 쳤다. 그땐 몰랐는데 지금은 당연하게 실무에서 적용하고 있는 패턴이 여기에 소개되어있어 신기했다. 그만큼 내용적으로 훌륭해서 다른 곳에서 재생산되어 나에게 왔다는 의미로 받아들여졌다. 알고 있는 패턴들을 다시 찬찬히 보며 생각할게 많아져서 이번에는 소단원 단위로 정리하겠다. 정적 팩터리 메서드 너무나도 유명하므로 장단점만 간단하게 짚어본다. 장점 첫째, 이름을 가질 수 있다..