분류 전체보기
-
클래스와 인터페이스 - 아이템 17. 변경 가능성을 최소화하라Study/Effective Java 2022. 12. 19. 17:54
변경 가능성을 최소화하라 불변 클래스란? 불변 클래스란 간단히 말해 그 인스턴스의 내부 값을 수정할 수 없는 클래스다. 불변 인스턴스에 간직된 정보는 고정되어 객체가 파괴되는 순간까지 절대 달라지지 않는다. Java의 String, 기본 타입의 박싱된 클래스들, BigInteger, BigDecimal이 여기에 속한다. 불변 클래스는 가변 클래스보다 설계하고 구현하고 사용하기 쉬우며, 오류가 생길 여지도 적고 훨씬 안전하다. 불변 클래스를 만들기 위한 다섯 가지 규칙 1. 객체의 상태를 변경하는 메서드(변경자)를 제공하지 않는다. 2. 클래스를 확장할 수 없도록 한다. 하위 클래스에서 부주의하게 혹은 나쁜 의도로 객체의 상태를 변하게 만드는 사태를 막아준다. 상속을 막는 대표적인 방법은 클래스를 fina..
-
클래스와 인터페이스 - 아이템 16. public 클래스에서는 public 필드가 아닌 접근자 메서드를 사용하라Study/Effective Java 2022. 12. 19. 11:29
public 클래스에서는 public 필드가 아닌 접근자 메서드를 사용하라 캡슐화의 이점을 제공하지 못하는 클래스 class Point { public int x; public int y; public Point(int x, int y) { this.x = x; this.y = y; } } 위와 같은 클래스는 데이터 필드에 직접 접근할 수 있으니, 캡슐화의 이점을 제공하지 못한다. API를 수정하지 않고는 내부 표현을 바꿀 수 없고, 불변식을 보장할 수 없으며, 외부에서 필드에 접근할 때 부수 작업을 수행할 수도 없다. 철저한 객체 지향 프로그래머는 이런 클래스를 상당히 싫어해서 필드들을 모두 private으로 바꾸고 public 접근자(getter)를 추가한다. 접근자와 변경자 메서드를 활용해 캡슐화한..
-
클래스와 인터페이스 - 아이템 15. 클래스와 멤버의 접근 권한을 최소화하라Study/Effective Java 2022. 12. 16. 17:49
클래스와 멤버의 접근 권한을 최소화하라 잘 설계된 컴포넌트란? 어설프게 설계된 컴포넌트와 잘 설계된 컴포넌트의 가장 큰 차이는 바로 클래스 내부 데이터와 내부 구현 정보를 외부 컴포넌트로부터 얼마나 잘 숨겼느냐이다. 잘 설계된 컴포넌트는 모든 내부 구현을 완벽히 숨겨, 구현과 API를 깔끔히 분리한다. 오직 API를 통해서만 다른 컴포넌트와 소통하며 서로의 내부 동작 방식에는 전혀 개의치 않는다. 정보 은닉, 혹은 캡슐화라고 하는 이 개념은 소프트웨어 설계의 근간이 되는 원리다. 정보 은닉이란? 정보 은닉이란 다른 객체로부터 자신의 정보를 숨기고 자신의 연산만을 통해 접근을 허용하는 것을 말한다. 정보 은닉은 시스템을 구성하는 컴포넌트들을 서로 독립시켜서 개발, 테스트, 최적화, 적용, 분석, 수정을 개..
-
모든 객체의 공통 메서드 - 아이템 14. Comparable을 구현할지 고려하라Study/Effective Java 2022. 12. 15. 14:17
Comparable을 구현할지 고려하라 Comparable의 compareTo 메서드 compareTo() 메서드는 Object의 메서드가 아니다. 특징 두 가지만 빼면 Object의 equals() 메서드와 동일하다. 그렇다면 무엇이 다를까? compareTo() 메서드는 단순 동치성 비교에 더해 순서까지 비교할 수 있으며, 제네릭하다. Comparable을 구현했다는 것은 그 클래스의 인스턴스들에는 자연적인 순서가 있음을 뜻한다. 그래서 Comparable을 구현한 객체들의 배열은 손쉽게 정렬이 가능하다. 사실상 자바 플랫폼 라이브러리의 모든 값 클래스와 열거 타입이 Comparable을 구현했다. 알파벳, 숫자, 연대 같이 순서가 명확한 값 클래스를 작성한다면 반드시 Comparable 인터페이스를..
-
모든 객체의 공통 메서드 - 아이템 13. clone 재정의는 주의해서 진행하라Study/Effective Java 2022. 12. 15. 13:55
clone 재정의는 주의해서 진행하라 개요 Cloneable은 복제해도 되는 클래스임을 명시하는 용도의 믹스인 인터페이스지만, 의도한 목적을 제대로 이루지 못했다. 가장 큰 문제는 clone() 메서드가 선언된 곳이 Cloneable이 아닌 Object이고, 그마저도 protected라는 데 있다. 따라서, Cloneable을 구현하는 것만으로는 외부 객체에서 clone() 메서드를 호출할 수 없다. 리플렉션을 사용하면 가능하지만, 100% 성공하는 것도 아니다. 해당 객체가 접근이 허용된 clone() 메서드를 제공한다는 보장이 없기 때문이다. 하지만, 이를 포함한 여러 문제점에도 불구하고 Cloneable 방식은 널리 쓰이고 있어서 잘 알아두는 것이 좋다. 이번 게시글에서는 clone() 메서드를 잘..
-
모든 객체의 공통 메서드 - 아이템 12. toString을 항상 재정의하라Study/Effective Java 2022. 12. 14. 14:38
toString을 항상 재정의하라 toString을 재정의해야 하는 이유 1. toString() 메서드를 재정의하지 않은 클래스에서는 적합한 문자열을 반환하지 않는다. 2. toString() 메서드를 재정의하지 않은 경우 "User@2d363fb3"와 같이 "클래스_이름@16진수로_표시한_해시코드"를 반환한다. 3. "User{name='홍길동'}"과 같이 객체의 정보를 직접 알려주는 형태가 훨씬 유익하다. 4. toString() 메서드를 잘 구현한 클래스는 사용하기에 훨씬 즐겁고, 해당 클래스를 사용한 시스템은 디버깅에 용이하다. 5. 직접 호출하지 않더라도 println(), printf(), 문자열 연결 연산자(+), assert 구문에 넘길 때 혹은 디버거가 객체를 출력할 때 등 자동으로 불..