분류 전체보기
-
클래스와 인터페이스 - 아이템 23. 태그 달린 클래스보다는 클래스 계층구조를 활용하라Study/Effective Java 2022. 12. 26. 17:07
태그 달린 클래스보다는 클래스 계층구조를 활용하라 태그 달린 클래스 public class Figure { enum Shape {RECTANGLE, CIRCLE}; // 태그 필드 - 현재 모양을 나타냄 final Shape shape; // 아래 필드들은 모양이 RECTANGLE일 때만 사용 double length; double width; // 아래 필드는 모양이 CIRCLE일 때만 사용 double radius; // RECTANGLE용 생성자 Figure(double length, double width) { shape = Shape.RECTANGLE; this.length = length; this.width = width; } // CIRCLE용 생성자 Figure(double radius)..
-
클래스와 인터페이스 - 아이템 22. 인터페이스는 타입을 정의하는 요도로만 사용하라Study/Effective Java 2022. 12. 26. 16:32
인터페이스는 타입을 정의하는 요도로만 사용하라 인터페이스의 용도 인터페이스는 자신을 구현한 클래스의 인스턴스를 참조할 수 있는 타입 역할을 한다. 즉, 클래스가 어떤 인터페이스를 구현한다는 것은 자신의 인스턴스로 무엇을 할 수 있는지를 클라이언트에 얘기해주는 것이다. 인터페이스는 오로지 이 용도로만 사용돼야 한다. 인터페이스의 잘못된 사용 public interface PhysicalConstants { static final double AVOGADROS_NUMBER = 6.022_140_857e23; static final double BOLZMANN_CONSTANT = 1.380_648_52e-23; static final double ELECTRON_MASS = 9.109_383-56e-31; }..
-
클래스와 인터페이스 - 아이템 21. 인터페이스는 구현하는 쪽을 생각해 설계하라Study/Effective Java 2022. 12. 26. 15:23
인터페이스는 구현하는 쪽을 생각해 설계하라 디폴트 메서드 Java 8 이전에는 기존 구현체를 깨뜨리지 않고는 인터페이스에 메서드를 추가할 방법이 없었다. Java 8 이후부터는 기존 인터페이스에 메서드를 추가할 수 있도록 디폴트 메서드가 추가되었다. 하지만, 위험이 완전히 사라진 것은 아니다. 디폴트 메서드를 선언하면, 그 인터페이스를 구현한 후 디폴트 메서드를 재정의하지 않은 모든 클래스에서 디폴트 구현이 쓰이게 된다. 즉, 디폴트 메서드는 구현 클래스에 대해 아무것도 모른 채 합의 없이 무작정 삽입될 뿐이라는 것이다. Java 8에서는 핵심 컬렉션 인터페이스들에 다수의 디폴트 메서드가 추가되었다. 주로 람다를 활용하기 위해서다. 자바 라이브러리의 디폴트 메서드는 코드 품질이 높고 범용적이라 대부분 상..
-
클래스와 인터페이스 - 아이템 20. 추상 클래스보다는 인터페이스를 우선하라Study/Effective Java 2022. 12. 21. 17:54
추상 클래스보다는 인터페이스를 우선하라 자바가 제공하는 다중 구현 메커니즘 자바가 제공하는 다중 구현 메커니즘은 인터페이스와 추상 클래스, 두 가지가 존재한다. Java 8부터는 인터페이스도 디폴트 메서드를 제공할 수 있게 되었다. 이제는 두 메커니즘 모두 인스턴스 메서드를 구현 형태로 제공할 수 있다. 추상 클래스 vs 인터페이스 둘의 가장 큰 차이는 추상 클래스가 정의한 타입을 구현하는 클래스는 반드시 추상 클래스의 하위 클래스가 되어야 한다는 점이다. 자바는 단일 상속만 지원하니, 추상 클래스 방식은 새로운 타입을 정의하는 데 커다란 제약을 안게 되는 셈이다. 반면, 인터페이스가 선언한 메서드를 모두 정의하고 그 일반 규약을 잘 지킨 클래스라면 다른 어떤 클래스를 상속했든 같은 타입으로 취급된다. ..
-
클래스와 인터페이스 - 아이템 19. 상속을 고려해 설계하고 문서화하라, 그러지 않았다면 상속을 금지하라Study/Effective Java 2022. 12. 21. 10:25
상속을 고려해 설계하고 문서화하라, 그러지 않았다면 상속을 금지하라 상속을 고려한 문서화와 설계 메서드를 재정의하면 어떤 일이 일어나는지를 정확히 정리하여 문서로 남겨야 한다. 달리 말하면, 상속용 클래스는 재정의할 수 있는 메서드들을 내부적으로 어떻게 이용하는지 문서로 남겨야 한다. 더 넓게 말하자면, 재정의 가능 메서드를 호출할 수 있는 모든 상황을 문서로 남겨야 한다. 여기서 재정의 가능 메서드란, public과 protected 메서드 중 final이 아닌 모든 메서드를 뜻한다. 1. @imlSpec 태그 메서드 주석에 붙여주면 자바독 도구가 "Implementation Requirements"로 시작하는, 메서드의 내부 동작 방식을 설명하는 절을 생성해 준다. 이 태그를 활성화하기 위해서는 명령..
-
클래스와 인터페이스 - 아이템 18. 상속보다는 컴포지션을 사용하라Study/Effective Java 2022. 12. 20. 17:17
상속보다는 컴포지션을 사용하라 상속의 문제점 상속은 코드를 재사용하는 강력한 수단이지만, 항상 최선은 아니다. 잘못 사용하면 오류를 내기 쉬운 소프트웨어를 만들게 된다. 일반적인 구체 클래스의 패키지 경계를 넘어, 즉 다른 패키지의 구체 클래스를 상속하는 일은 위험하다. 이번 게시글의 '상속'은 특정 클래스가 다른 클래스를 확장하는 구현 상속을 의미한다. 메서드 호출과 달리 상속은 캡슐화를 깨뜨린다. 다르게 말하면, 상위 클래스가 어떻게 구현되느냐에 따라 하위 클래스의 동작에 이상이 생길 수 있다. 상위 클래스는 릴리스마다 내부 구현이 달라질 수 있으며, 그 여파로 코드 한 줄 건드리지 않은 하위 클래스가 오동작할 수 있다는 말이다. 또한, 상위 클래스와 하위 클래스의 관계가 컴파일 시점에 결정되어 구현..