언어/Effective Java
-
이펙티브 자바 Item6 - 불필요한 객체 생성을 피하라언어/Effective Java 2024. 5. 27. 16:35
불필요한 객체 생성을 피하면서 자원을 절약해야한다.같은 기능의 객체를 새로 생성하는 대신, 객체 하나를 재사용하는 편이 나을 때가 많다.특히, 불변 객체는 언제든지 재사용할 수 있다. 같은 기능 수행하는 객체에 대한 재사용 강조싱글톤 사용 (내가 구현할 때)static factory 메서드 사용 (구현된 것을 사용할 때)객체 캐싱 (무거운 객체일 때 미리 초기화 혹은 flyweight 패턴 고려) 같은 인스턴스 대변하는 여러 타입을 굳이 만들지 말 것 박싱 클래스는 꼭 필요한 경우만 사용 1. 문자열 객체 생성 같은 값임에도 다른 래퍼런스인 경우 - 기존 인스턴스를 재사용하자 문자열의 경우 항상 new 로 새로운 문자열을 생성하기 보다 같은 문자열이라면, "java"처럼 리터럴로 생성한다. 2. s..
-
이펙티브 자바 Item5 - 자원을 직접 명시하지 말고 의존 객체 주입을 사용하라언어/Effective Java 2024. 5. 27. 15:54
사용하는 자원에 따라 동작이 달라지는 클래스는 정적 유틸리티 클래스나 싱글턴 방식이 적합하지 않다. 1. 자원 직접 주입 대부분의 클래스는 여러 리소스에 의존한다. 책에서는 SpellChecker와 Dictionary를 예로 든다.두 객체 사이에는 의존관계가 있다. 아래는 static 유틸리티를 잘못 사용한 예이다. - 이는 유연하지 않고 테스트가 어렵다.public class SpellChecker { private static final Lexicon dictionary = ...; // 의존하는 리소스 (의존성) private SpellChecker() {} // 객체 생성 방지 public static boolean isValid(String word) { ... } public static..
-
이펙티브 자바 Item3 - private 생성자나 열거타입으로 싱글톤임을 보장하라언어/Effective Java 2024. 5. 27. 15:18
싱글톤이란, 인스턴스를 오직 하나만 생성할 수 있는 클래스를 의미한다.싱글톤을 사용하는 클라이언트는 테스트가 어렵다. 하나의 자원을 공유하기 때문에 테스트로 써도 되는 클래스인가를 판별해야하기 때문이다. (ex DB 접근하는 싱글톤을 테스트에 적용하면 안된다) 서버 환경에서는 싱글톤이 하나만 만들어지는 것을 보장하지 못한다.서버에서 클래스 로더를 어떻게 구성하고 있느냐에 따라 JVM이 분산되어 여러개 있을 경우 싱글톤 클래스임에도 불구하고 하나 이상의 오브젝트가 만들어질 수 있다.싱글톤의 사용은 전역 상태를 만들 수 있기 때문에 바람직하지 못하다.아무 객체나 자유롭게 접근하고 수정하고 공유할 수 있는 전역 상태를 갖는 것은 객체지향 프로그래밍싱글톤을 만드는 방식 1.public static 멤버가 fin..
-
이펙트브 자바 Item4 - 인스턴스화를 막으려거든 private 생성자를 사용하라언어/Effective Java 2024. 5. 27. 12:24
자바는 생성자를 선언하지 않으면, 기본으로 default 생성자를 만든다. (매개변수 x 생성자)따라서, 생성자를 안만든다고 객체를 못만드는 것은 아니다. 객체를 생성하기 싫다면, private 생성자를 통해 이를 반드시 막아라 * * This class contains various methods for manipulating arrays (such as * sorting and searching). This class also contains a static factory * that allows arrays to be viewed as lists. */// Suppresses default constructor, ensuring non-instantiability.private Arrays() ..
-
이펙티브 자바 Item2 - 생성자에 매개변수가 많다면 빌더를 고려하라언어/Effective Java 2024. 5. 27. 11:44
정적 팩토리와 생성자는 "선택적 매개변수"가 많을 때 적절하게 대응하기 어렵다는 단점이 있다. 만약 있을 수도 없을 수도 있는 필드가 많은 객체가 있다고 한다면.. 1. 점층적 생성자 패턴 필수 매개변수를 받는 생성자 1개, 그리고 선택 매개변수를 하나씩 늘려가며 생성자를 만드는 패턴이다. public class Javabom { private Long id; private List members; private String email; private LocalDateTime createDateTime; private boolean isOpen; public Javabom(Long id, List members, String email, LocalDateTime crea..
-
이팩티브 자바 Item 1 - 생성자 대신 정적 팩터리 메서드를 고려하라언어/Effective Java 2024. 5. 27. 11:06
인스턴스를 생성하는 방법은 (1) public 생성자 (2) 정적 팩터리 메서드 사용이 있다. 이때, 정적 팩터리 메서드 메서드를 사용하면 다음과 같은 장점이 있다.1. 생성 목적에 대한 이름 표현이 가능하다. (객체 생성의 가독성이 높아진다) 생성자는 클래스명으로만 구현할 수 있지만, 정적팩터리 메서드는 자신의 이름을 가질 수 있다.new 키워드를 통해 생성자를 생성하면, 해당 생성자의 인수 순서와 내부구조를 알고 있어야 목적에 맞게 객체를 생성할 수 있다는 번거로움 존재정적 팩터리 메서드 구현 시 자주 사용되는 이름이 있다! from: 매개변수를 받아서 해당 타입의 인스턴스 반환of: 여러 매개변수 받아서 적합한 인스턴스 반환valueOf : from, of보다 자세한 버전 instance, get..