책/이펙티브 자바
-
item 10 equals는 일반 규약을 지켜 재정의하라책/이펙티브 자바 2022. 2. 22. 14:43
ITEM 10 equals는 일반 규약을 지켜 재정의하라 equals 메서드를 재정의 하지않는 경우 다음과 같은 경우에 equals 메서드를 재정의 하지 않는것이 최선이다 각 인스터스가 본질적으로 고유하다 값이 아니라 동작하는 개체를 표현하는 클래스 Thread 가 좋은 예시이다 인스턴스의 논리적 동치성을 검사할 필요가 없다 설계자의 의도에 따라 기본 equals 만으로 해결이 가능 어떠한 값을 검사 할때 꼭 같은 정규표현식을 쓸 필요는 없을수도 있다(논리적 동치성 검사가 필요 없을 수 있다는 것) 상위 클래스에서 재정의한 equals 메서드가 하위 클래스에도 딱 들어 맞는다 Set, List, Map 등의 구현체들은 상위 클래스에서 구현한 equals 메서드를 상속 받아 사용한다 AbstractSet ..
-
item 9 try-finally보다는 try-with-resources를 사용하라책/이펙티브 자바 2022. 2. 21. 20:17
ITEM 9 try-finally보다는 try-with-resources를 사용하라 자원 닫기의 안전망으로 finalizer를 활용하는 경우가 많지만 item8에서 봤듯이 믿을만 하지 못하다 전통적으로 자원을 제대로 닫을때 사용하던 방법은 try-finally이다 예외가 발생하거나 메서드에서 반환되는 경우도 마찬가지static String firstLineOfFile(String path) throws IOException { BufferedReader br = new BufferedReader(new FileReader(path)); try { return br.readLine(); } finally { br.close(); } } 자원이 많아지면 지저분해진다static void copy(String ..
-
item 8 finalizer와 cleaner사용을 피하라책/이펙티브 자바 2022. 2. 18. 22:47
ITEM 8 finalizer와 cleaner사용을 피하라 finalizer는 기본적으로 쓰지 말아야 하며 java9에서는 사용자제 api로 지정했다 finalizer와 cleaner를 피하는 이유 즉시 실행된다는 보장이 없으며 실행 시점을 예측하기가 어렵다 상황에 따라 위험한 경우가 있어서 일반적으로는 불필요하다 정확한 시점에 실행되어야 하는 작업은 절대 할 수 없다 얼마나 빠르게 수행이 될지는 GC 알고리즘에 달려있고 GC 구현마다 천차만별이다 수행 시점 뿐 아니라 수행 여부도 보장하지 않는다 상태를 영구적으로 수정하는 작업에서는 절대 사용하지 말자 DB 영구 락 해제를 맡겼다가 분산 시스템 전체가 서서히 멈출수도 있다 동작 중 발생한 에러는 무시되며 처리할 작업이 남아 있어도 그 순간 종료된다 fi..
-
item 7 다 쓴 객체 참조를 해제하라책/이펙티브 자바 2022. 2. 17. 14:05
ITEM 7 다 쓴 객체 참조를 해제하라 GC에 너무 의존하지 말자 메모리 누수가 일어나는 상황 아래의 Stack을 구현한 간단한 예제로 메모리 누수가 발생하는 상황을 살펴보자 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..
-
item 6 불필요한 객체 생성을 피하라책/이펙티브 자바 2022. 2. 16. 09:01
ITEM 6 불필요한 객체 생성을 피하라 같은 기능의 객체라면 매번 생성 하는것 보다는 객체를 재사용 하자 객체 재사용은 성능상 이점을 가져다준다 안좋은예시 String str = new String("hello"); 위와 같은 코드는 실행시 매번 hello 라는 값을 가진 인스턴스를 새로 만들게 된다 인자로 들어가는 hello는 이미 만들려고 하는것 그 자체이다 전혀 쓸데 없는 행위이다 개수가 많아진다면 그만큼 쓸데없는 String 인스턴스가 생길것이다 좋은예시 String str = "hello"; 위의 코드는 첫번째 예시와 같은 결과를 도출한다 위의 코드는 인스턴스를 한번만 생성하고 재사용 하기 때문에 불필요한 인스턴스에 생성을 방지한다 또한 위의 코드는 같은 가상머신 내에서 이러한 문자열 리터럴을..
-
item 5 자원을 직접 명시하지 말고 의존 객체 주입을 사용하라책/이펙티브 자바 2022. 2. 15. 20:51
ITEM 5 자원을 직접 명시하지 말고 의존 객체 주입을 사용하라 자원을 코드에 직접 명시하지 말자 java로 개발을 하다 보면 많은 클래스가 여러개의 자원에 의존하게 된다 이런 경우 의존성을 코드에 명시하게 되면 클라이언트와 의존성이 강하게 결합된다 유연하지 않은 코드가 되며 테스트도 어려워진다 정적 유틸리티를 잘못 사용한 예제이다 public class SpellChecker { private static final Lexicon dictionary = ...; private SpellChecker() {} public static boolean isValid(String word) { ... } public static List suggestions(String typo) { ... } } 싱글턴을..
-
item 4 인스턴스화를 막으려거든 private 생성자를 사용하라책/이펙티브 자바 2022. 2. 14. 18:10
ITEM 4 인스턴스화를 막으려거든 private 생성자를 사용하라 정적 메서드와 정저 필드만이 있는 클래스가 있다 인스턴스를 생성하지 못하게 해야되는 클래스가 필요한 경우가 있다 ex) 배열 관련 메서드를 모아놓은 클래스 java.util.Arrays public class Arrays { private static final int MIN_ARRAY_SORT_GRAN = 1 toIndex) { throw new IllegalArgumentException( "fromIndex(" + fromIndex + ") > toIndex(" + toIndex + ")"); } if (fromIndex < 0) { throw new ArrayIndexOutOfBoundsException(fromIndex); } ..
-
item 3 private 생성자나 열거 타입으로 싱글턴임을 보증하라책/이펙티브 자바 2022. 2. 11. 22:17
ITEM 3 private 생성자나 열거타입으로 싱글턴임을 보증하라 싱글턴 인스턴스를 오직 하나만 생성할 수 있는 클래스 함수와 같은 무상태 객체, 유일해야 하는 시스템 컴포넌트 등 mock 구현이 안되기 때문에 클라이언트 테스트가 어려울수있다 장점 객체를 한번만 생성 후 재사용 하기 때문에 메모리 낭비를 방지할 수 있고 다른 객체와 공유도 가능하다단점 인터페이스로 만든 후 해당 인터페이스를 구현한 싱글턴이 아니면 mock 구현이 안되기 때문에 클라이언트 테스트가 어렵다 싱글턴 생성 방식 public static final 필드 public class Foo { public static final Foo INSTANCE = new Foo(); private Foo() {} public void getPr..
-
item 2 생성자에 매개변수가 많다면 빌더를 고려하라책/이펙티브 자바 2022. 2. 10. 20:47
ITEM 2 생성자에 매개변수가 많다면 빌더를 고려하라 정적 팩터리 패턴과 생성자는 매개변수가 많을 때 가독성이 떨어지게 된다 이럴때 점층적 생성자 패턴, 자바 빈즈 패턴, 빌더 패턴을 사용해보자 점층적 생성자 패턴 public class Foo { private String userName; //필수값 private int age; //필수값 private String address; //필수값 private String tel; //선택값 public Foo(String userName) { this.userName = userName; } public Foo(String userName, int age) { this.userName = userName; this.age = age; } public ..
-
item 1 생성자 대신 정적 팩터리 메서드를 고려하라책/이펙티브 자바 2022. 2. 9. 23:40
ITEM 1 생성자 대신 정적 팩터리 메서드를 고려하라. 생성자를 이용하여 객체 생성 public class Foo { private String name; public Foo(String name) { this.name = name; } } 위와 같이 생성자를 통해 객체를 생성 하는 경우 아래와 같이 호출부에서 이 객체의 역할을 알기가 힘들다 public static void main(String[] args) { Foo foo1 = new Foo("hong"); } 생성자의 개수가 더 많아진다면 ? public class Foo { private String name; private int age; public Foo(String name) { this.name = name; } public Foo(..