언어
-
이펙티브 자바 Item 26,27,28 (제네릭 관련)언어/Effective Java 2024. 6. 4. 11:30
Item 26 (로 타입은 사용하지 마라) 로타입은 List list = new ArrayList(); 형태로 사용하는 방식이다.매개변수화 타입은 List list = new ArrayList(); 방식 로타입은 뭐든지 다 들어간다. List list = new ArrayList(); list.add("문자열"); list.add(1); String text = (String) list.get(0); Integer number = (Integer) list.get(1); 문자열, 숫자 가리지 않고 다 넣을 수 있다. 하지만, 타입 캐스팅해줘야하는 경우가 빈번해진다. 제네릭을 통해 타입 안정..
-
이펙티브 자바 Item 25 - 톱레벨 클래스는 한파일에 하나만 담자언어/Effective Java 2024. 6. 4. 11:17
톱레벨 클래스는 한 파일에 하나만 담자 톱레벨 클래스를 여러개 선언하면 이득은 없고 심각한 위험만 발생할 수 있다. 한 클래스를 여러개로 정의할 수 있으며, 그 중 어느것을 사용할지는 어느 소스파일을 먼저 컴파일하냐에 따라 달라지기 때문이다. 톱레벨 클래스 중복정의 Utensil과 Dessert참조 하는 Main 클래스 public class Main { public static void main(String[] args) { System.out.println(Utensil.NAME + Dessert.NAME); }} class Utensil { static final String NAME = "pan";}class Dessert { static final Strin..
-
이펙티브 자바 Item 24 - 멤버 클래스는 되도록 static으로 만들라언어/Effective Java 2024. 6. 4. 10:52
중첩 클래스는 다른 클래스 안에 정의된 클래스다. 중첩 클래스는 자신을 감싼 바깥 클래스에서만 쓰여야 하며, 그 외의 쓰임새가 있다면 톱레벨 클래스로 만들어야 한다. 중첩 클래스 종류 정적 멤버 클래스(비정적)멤버 클래스익명 클래스 지역 클래스 정적 멤버 클래스를 제외한 나머지는 내부 클래스(inner class)다.정적 멤버 클래스 클래스 내부에 static으로 선언된 클래스다.다른 클래스 안에 선언되고, 바깥 클래스의 private 멤버에도 접근 가능. 그 외는 일반 클래스와 같다.private으로 선언 시 바깥 클래스에서만 접근 가능하다. public class Animal { private String name = "cat"; // 열거 타입도 암시적 static public en..
-
이펙티브 자바 - Item 21 - 인터페이스는 구현하는 쪽을 고려해서 설계하라언어/Effective Java 2024. 6. 4. 09:20
인터페이스에 메서드 추가 자바 8 전에는 기존 구현체를 깨뜨리지 않고 인터페이스에 메서드를 추가할 방법은 존재하지 않았다. 자바 8부터 디폴트 메서드를 통해서 기존 인터페이스에 메서드를 추가할 수 있게 되었다.디폴트 메서드를 선언하면, 그 인터페이스를 구현한 후 디폴트 메서드를 재정의하지 않은 모든 클래스에서 디폴트 구현이 쓰이게 된다.단, 이렇게 디폴트 메서드를 추가한다고해도 기존 구현체들과 매끄럽게 연동된다는 보장은 없다. 생각할 수 있는 모든 상황에서 불변식을 해치지 않는 디폴트 메서드를 작성하기란 어렵기 때문이다. default boolean removeIf(Predicate filter) { Objects.requireNonNull(filter); boolean res..
-
이펙티브 자바 Item 20 - 추상클래스보다는 인터페이스를 우선시하라언어/Effective Java 2024. 5. 31. 11:45
1. 자바 제공 다중 구현 메커니즘자바가 제공하는 다중구현 메커니즘은 추상클래스와 인터페이스 두가지다.자바 8부터 인터페이스도 디폴드 메서드를 제공할 수 있게되어, 이제 두 메커니즘 모두 인스턴스 메서드를 구현형태로 제공할 수 있다. 2. 추상클래스와 인터페이스 차이 추상클래스가 정의한 타입을 구현하는 클래스는 반드시 추상클래스의 하위클래스가 되어야한다.만약 두 클래스가 아무런 관계가 없는데 상속해야한다면, 혼란을 줄 수 있다. 자바는 단일 상속만 지원하므로, 추상 클래스 방식은 새로운 타입을 정의해야하는 제약을 가진다.반면 인터페이스가 선언한 메서드를 모두 정의하고 일반 규약을 잘 지킨 클래스라면 다른 어떤 클래스를 상속했든 같은 타입으로 취급된다. 인터페이스 : 다중 상속 가능, 구현한 클래스와 같은..
-
이펙티브 자바 Item 18 - 상속보다는 컴포지션을 사용하라언어/Effective Java 2024. 5. 31. 10:35
1. 구체 클래스 상속의 위험성 다른 패키지의 구체 클래스를 상속하는 일은 위험하다 (인터페이스 상속말고, 구현 상속)메서드 호출과 달리 상속은 캡슐화를 깨뜨린다.상위 클래스에 따라 하위클래스의 동작에 문제가 생길 수 있기 때문이다.하위클래스가 깨지기 쉬운 이유 상위 클래스의 메서드를 재정의 하여 하위 클래스의 로직을 방어한다. 상위 클래스의 메서드를 동작을 다시 구현하는게 어렵다.오류나 성능을 떨어뜨릴 수도 있다.하위 클래스에서 접근 불가한 private 클래스를 써야한다면 구현이 불가능하다.상위 클래스 릴리즈에서 새로운 메서드를 추가했을 때를 고려해야함하위 클래스에서 허용되지 않은 원소를 추가할 지도 모른다!! 하위 클래스에 추가한 새 메서드가, 상위 클래스 다음 릴리즈에서 같은 시그니처를 가질 때..
-
이펙티브 자바 Item 17 - 변경 가능성을 최소화하라언어/Effective Java 2024. 5. 30. 16:13
불변 클래스는 별다른 동기화 방법을 적용하지 않았다 해도 어느 쓰레드에서건 마음껏 안전하게 사용할 수 있다. 불변 클래스란 그 인스턴스의 내부 값을 수정할 수 없는 클래스를 의미한다. 불변 인스턴스에 간직된 정보는 고정되어 객체가 파괴되는 순간까지 절대 달라지지 않는다. String, 기본 타입의 박싱된 클래스, BigInteger, BigDecimal 등이 여기에 속한다. 클래스를 불변으로 만들려면 다음 다섯 규칙을 따르면 된다. 객체의 상태를 변경하는 메서드를 제공하지 않는다.클래스를 확장할 수 없도록 한다.하위 클래스에서 부주의하게 혹은 나쁜 의도로 객체의 상태를 변하게 만드는 상태를 막아준다. 상속을 막는 대표적인 방법은 클래스를 final로 선언하는 것이지만 다른 방법도 살펴보자모든 필드를 f..
-
이펙티브 자바 Item 16 - public 클래스에서는 public필드가 아닌 접근자 메서드를 사용하라언어/Effective Java 2024. 5. 30. 09:52
1. 접근자 메서드를 활용한 데이터 캡슐화 대표적인 클래스 작성 실수: 인스턴스 필드만을 모아놓은 퇴보한 클래스 인스턴스 필드만을 모아놓은 클래스는 데이터 직접 접근할 수 있으나 캡슐화의 이점을 제공하지 못한다.public class Point { public double x; public double y;} 캡슐화가 전혀 안되기 때문에 아래와 같은 단점을 수반한다. API를 수정하지 않고는 내부 표현을 바꿀 수 없다. 불변식을 보장하지 못한다.외부에서 필드에 접근할 때 부수작업을 수행할 수 없다.*API 수정부분 Point.getValue() 같은 메서드를 호출해서 x,y를 얻는다고 했을 때 내부 구현 로직이 캡슐화되어 있기 때문에 얼마든지 바꿀 수 있음 Point.x로 접근했을 때, 만약 ..