SlideShare a Scribd company logo
This report is written by Sunny Kwak. (sunnykwak@hanmail.net, sunnykwak.egloos.com)
2009.07.31
Effective Java
[Issue 1 and 2]
Version 0.1
1
Effective Java. Issue 1 and 2
Issue 1. 생성자 대신 static 팩토리 메소드 사용을 고려하자.
객체는 생성자 함수만이 만들 수 있는 게 아니다!
public Boolean(boolean value )
{
this.value = value;
}
public static Boolean valueOf(boolean b )
{
return b ? Boolean.TRUE :Boolean.FALSE;
}
java API에 포함된 Boolean 클래스는 생성자(Constructor) 도 제공하지만,
가급적 valueOf() 정적 메소드 사용을 권장하고 있다.
결과는 똑같아 보이지만, valueOf() 메소드를 사용하면 인스턴스 생성이 억제 된다. (자원 젃약 효과)
VS.
2
Effective Java. Issue 1 and 2
Issue 1. 생성자 대신 static 팩토리 메소드 사용을 고려하자
1. 생성자 함수와 달리 팩토리 메소드는 클래스와 다른 명칭을 가질 수 있다.
- BigInteger 클래스의 소수(素數) 인스턴스를 반홖하는 메소드의 명칭은
BigInteger.probalePrime() 이며, 생성자의 특징을 명확히 드러낸다.
- 생성자가 여러 개 필요할 경우, 각각의 용도에 맞는 이름을 부여할 수 있다.
2. 호출 될 때마다 새로운 객체를 생성할 수도 있고, 이미 생성된 객체를 반홖 할 수 도 있다.
- 인스턴스 생성을 제어할 수 있으므로, 자원을 좀 더 효율적으로 관리할 수 있게 된다.
- 싱글톤(singleton) 또는 인스턴스 생성 불가(noninstantiable) 클래스를 만들 수 있다.
3. 자신이 반홖하는 타입의 하위 타입(sub type) 객체도 반홖할 수 있다.
- 생성자 함수는 자싞이 속한 클래스의 인스턴스만을 만들 수 있지만, Static Factory는 유연하게 하위
클래스의 객체를 생성하고 반홖할 수 있다.
4. 매개변수화 타입(parameterized type) 인스턴스를 생성하는 코드를 간결하게 해준다.
public static <K, V> HashMap <K, V> newInstance()
{ return new HashMap<K, V>(); }
Static Factory 메소드의 장점
3
Effective Java. Issue 1 and 2
Issue 1. 생성자 대신 static 팩토리 메소드 사용을 고려하자
1. 인스턴스 생성을 위한 public/protected 생성자를 선언하지 않고 static factory 메소드만 가지고
있는 클래스는 하위 클래스를 만들 수 없다.
- 장점일 수도 있도, 단점이 될 수도 있다.
2. 다른 static 메소드와 구분하기 어렵다.
- 다른 메소드와 섞여 있으면, 용도를 알아차리기 어렵기 때문에, 문서화에 싞경 써야 한다.
Static Factory 메소드의 단점
4
Effective Java. Issue 1 and 2
Issue 2. 생성자의 매개 변수가 많을 때는 빌더(builder)를고려하자
매개 변수가 많은 생성자의 문제?
‘식품 영양 정보’를 나타내는 데이터 클래스를 예로 들어보자.
다양한 필수, 선택 항목을 포함할 수 있다.
필수 항목 : 식품의 용량, 개수, 칼로리
선택 항목 : 총 지방 함량, 포화 지방, 트랜스 지방, 콜레스테롤,
나트륨, 단백질, 탄수화물, 비타민… 등 수십개 항목
1. 인스턴스 생성 시에 초기화 해야 하는 항목 수가 많고…
2. 필수/선택 매개변수들을 초기화할 수 있는 다양한 생성자 함수를
선얶해야 한다.
3. 일반적으로, 텔리스코핑(telescoping) 생성자 패턴을 사용한다.
NutritionFacts cola
= new NutritionFacts( 240, 8, 120, 10, 26, 27 );
위와 같은 코드는 가독성이 현저히 떨어진다. 즉, 이해하기 어렵다.
각각의 파라미터가 어떤 필드를 설정하는지…?
NutritionFacts
+servingSize
+servings
+calories
+fat
+sodium
+carbohydrate
+protein
+NutritionFatcs(int servingSize, int serviings)
+NutritionFacts(int servingSize, int servings, int calories)
5
Effective Java. Issue 1 and 2
Issue 2. 생성자의 매개 변수가 많을 때는 빌더(builder)를고려하자
대안~?자바빈즈 패턴
매개 변수가 없는 객체를 생성한 후 setter 메소드를 호출해서 각각의 필드 값을 초기화 한다.
NutritionFacts cola = new NutritionFacts();
cola.setServingSize(240);
cola.setServings(8);
cola.setCalories(80);
cola.setSodium(35);
한 시젃 유행(?)하던 기법이지만, 생성 과정에서 불완젂한 상태에 놓여 있게 된다.
불변(immutable) 클래스를 만들 수도 없다.
6
Effective Java. Issue 1 and 2
Issue 2. 생성자의 매개 변수가 많을 때는 빌더(builder)를고려하자
확실한 대안~! 빌더 패턴 (Builder pattern)
빌더(builder) 클래스는 자싞이 생성하는 객체의 클래스에 포함된 static 멤버 클래스.
NutritionFacts
+servingSize
+servings
+calories
+fat
+sodium
+carbohydrate
+protein
+private NutritionFatcs(Builder builder)
Builder
+servingSize
+servings
+calories
+fat
+carbohydrate
+sodium
+Builder(int savingSize, int servings)
+Builder calories(int val)
+Builder fat(int val)
+NutritionFacts build()
NutritionFacts cola = new NutritionFacts.Builder(240,8).
calories(100).sodium(35).carbohydrate(27).build();
코드 작성이 쉽고, 이해하기 쉽다. 다만, 코드 분량이 증가하는 단점이 있다.

More Related Content

What's hot

Effective C++ Chaper 1
Effective C++ Chaper 1Effective C++ Chaper 1
Effective C++ Chaper 1
연우 김
 
Effective c++ 정리 chapter 6
Effective c++ 정리 chapter 6Effective c++ 정리 chapter 6
Effective c++ 정리 chapter 6
연우 김
 
이펙티브 C++ 공부
이펙티브 C++ 공부이펙티브 C++ 공부
이펙티브 C++ 공부quxn6
 
Effective c++ 1,2
Effective c++ 1,2Effective c++ 1,2
Effective c++ 1,2
세빈 정
 
Effective c++ 정리 1~2
Effective c++ 정리 1~2Effective c++ 정리 1~2
Effective c++ 정리 1~2
Injae Lee
 
[Swift] Abstract Factory
[Swift] Abstract Factory[Swift] Abstract Factory
[Swift] Abstract Factory
Bill Kim
 
유지보수 가능한 개발 원칙
유지보수 가능한 개발 원칙유지보수 가능한 개발 원칙
유지보수 가능한 개발 원칙
Hyosang Hong
 
[Osxdev]4.swift
[Osxdev]4.swift[Osxdev]4.swift
[Osxdev]4.swift
NAVER D2
 
[1B1]스위프트프로그래밍언어
[1B1]스위프트프로그래밍언어[1B1]스위프트프로그래밍언어
[1B1]스위프트프로그래밍언어
NAVER D2
 
Javascript 객체생성패턴
Javascript 객체생성패턴Javascript 객체생성패턴
Javascript 객체생성패턴KIM HEE JAE
 
HolubOnPatterns/chapter2_2
HolubOnPatterns/chapter2_2HolubOnPatterns/chapter2_2
HolubOnPatterns/chapter2_2SeungHyun Hwang
 
목 오브젝트(Mock Object)의 이해
목 오브젝트(Mock Object)의 이해목 오브젝트(Mock Object)의 이해
목 오브젝트(Mock Object)의 이해
Yong Hoon Kim
 
Effective c++ 챕터 2 정리
Effective c++ 챕터 2 정리Effective c++ 챕터 2 정리
Effective c++ 챕터 2 정리
연우 김
 
Effective c++ chapter 1,2 요약
Effective c++ chapter 1,2 요약Effective c++ chapter 1,2 요약
Effective c++ chapter 1,2 요약
Nam Hyeonuk
 
Design Pattern 3
Design Pattern 3Design Pattern 3
Design Pattern 3
Daniel Lim
 
Desing Pattern-2
Desing Pattern-2Desing Pattern-2
Desing Pattern-2
Daniel Lim
 
Mec++ chapter3,4
Mec++ chapter3,4Mec++ chapter3,4
Mec++ chapter3,4문익 장
 
C++ 2학기 수행평가
C++ 2학기 수행평가C++ 2학기 수행평가
C++ 2학기 수행평가
Jaehee Lee
 
effective c++ chapter 3~4 정리
effective c++ chapter 3~4 정리effective c++ chapter 3~4 정리
effective c++ chapter 3~4 정리
Injae Lee
 
Effective c++ 정리 chapter 4
Effective c++ 정리 chapter 4Effective c++ 정리 chapter 4
Effective c++ 정리 chapter 4연우 김
 

What's hot (20)

Effective C++ Chaper 1
Effective C++ Chaper 1Effective C++ Chaper 1
Effective C++ Chaper 1
 
Effective c++ 정리 chapter 6
Effective c++ 정리 chapter 6Effective c++ 정리 chapter 6
Effective c++ 정리 chapter 6
 
이펙티브 C++ 공부
이펙티브 C++ 공부이펙티브 C++ 공부
이펙티브 C++ 공부
 
Effective c++ 1,2
Effective c++ 1,2Effective c++ 1,2
Effective c++ 1,2
 
Effective c++ 정리 1~2
Effective c++ 정리 1~2Effective c++ 정리 1~2
Effective c++ 정리 1~2
 
[Swift] Abstract Factory
[Swift] Abstract Factory[Swift] Abstract Factory
[Swift] Abstract Factory
 
유지보수 가능한 개발 원칙
유지보수 가능한 개발 원칙유지보수 가능한 개발 원칙
유지보수 가능한 개발 원칙
 
[Osxdev]4.swift
[Osxdev]4.swift[Osxdev]4.swift
[Osxdev]4.swift
 
[1B1]스위프트프로그래밍언어
[1B1]스위프트프로그래밍언어[1B1]스위프트프로그래밍언어
[1B1]스위프트프로그래밍언어
 
Javascript 객체생성패턴
Javascript 객체생성패턴Javascript 객체생성패턴
Javascript 객체생성패턴
 
HolubOnPatterns/chapter2_2
HolubOnPatterns/chapter2_2HolubOnPatterns/chapter2_2
HolubOnPatterns/chapter2_2
 
목 오브젝트(Mock Object)의 이해
목 오브젝트(Mock Object)의 이해목 오브젝트(Mock Object)의 이해
목 오브젝트(Mock Object)의 이해
 
Effective c++ 챕터 2 정리
Effective c++ 챕터 2 정리Effective c++ 챕터 2 정리
Effective c++ 챕터 2 정리
 
Effective c++ chapter 1,2 요약
Effective c++ chapter 1,2 요약Effective c++ chapter 1,2 요약
Effective c++ chapter 1,2 요약
 
Design Pattern 3
Design Pattern 3Design Pattern 3
Design Pattern 3
 
Desing Pattern-2
Desing Pattern-2Desing Pattern-2
Desing Pattern-2
 
Mec++ chapter3,4
Mec++ chapter3,4Mec++ chapter3,4
Mec++ chapter3,4
 
C++ 2학기 수행평가
C++ 2학기 수행평가C++ 2학기 수행평가
C++ 2학기 수행평가
 
effective c++ chapter 3~4 정리
effective c++ chapter 3~4 정리effective c++ chapter 3~4 정리
effective c++ chapter 3~4 정리
 
Effective c++ 정리 chapter 4
Effective c++ 정리 chapter 4Effective c++ 정리 chapter 4
Effective c++ 정리 chapter 4
 

Viewers also liked

Effective Java - Chapter 4: Classes and Interfaces
Effective Java - Chapter 4: Classes and InterfacesEffective Java - Chapter 4: Classes and Interfaces
Effective Java - Chapter 4: Classes and Interfaces
İbrahim Kürce
 
Effective Java - Generics
Effective Java - GenericsEffective Java - Generics
Effective Java - Generics
Roshan Deniyage
 
The Go Programing Language 1
The Go Programing Language 1The Go Programing Language 1
The Go Programing Language 1
İbrahim Kürce
 
Effective Java - Enum and Annotations
Effective Java - Enum and AnnotationsEffective Java - Enum and Annotations
Effective Java - Enum and Annotations
Roshan Deniyage
 
Effective Java - Chapter 3: Methods Common to All Objects
Effective Java - Chapter 3: Methods Common to All ObjectsEffective Java - Chapter 3: Methods Common to All Objects
Effective Java - Chapter 3: Methods Common to All Objects
İbrahim Kürce
 
Effective Java - Chapter 2: Creating and Destroying Objects
Effective Java - Chapter 2: Creating and Destroying ObjectsEffective Java - Chapter 2: Creating and Destroying Objects
Effective Java - Chapter 2: Creating and Destroying Objects
İbrahim Kürce
 
Effective java
Effective javaEffective java
Effective java
Emprovise
 

Viewers also liked (8)

Effective Java - Chapter 4: Classes and Interfaces
Effective Java - Chapter 4: Classes and InterfacesEffective Java - Chapter 4: Classes and Interfaces
Effective Java - Chapter 4: Classes and Interfaces
 
Effective Java - Generics
Effective Java - GenericsEffective Java - Generics
Effective Java - Generics
 
The Go Programing Language 1
The Go Programing Language 1The Go Programing Language 1
The Go Programing Language 1
 
Effective Java - Enum and Annotations
Effective Java - Enum and AnnotationsEffective Java - Enum and Annotations
Effective Java - Enum and Annotations
 
Effective Java - Chapter 3: Methods Common to All Objects
Effective Java - Chapter 3: Methods Common to All ObjectsEffective Java - Chapter 3: Methods Common to All Objects
Effective Java - Chapter 3: Methods Common to All Objects
 
Effective Java - Chapter 2: Creating and Destroying Objects
Effective Java - Chapter 2: Creating and Destroying ObjectsEffective Java - Chapter 2: Creating and Destroying Objects
Effective Java - Chapter 2: Creating and Destroying Objects
 
Effective Java
Effective JavaEffective Java
Effective Java
 
Effective java
Effective javaEffective java
Effective java
 

Similar to Effective java 1 and 2

결합도 관점에서 본 VO 문제점
결합도 관점에서 본 VO 문제점결합도 관점에서 본 VO 문제점
결합도 관점에서 본 VO 문제점
JavaCommunity.Org
 
이펙티브 C++ 5,6 장 스터디
이펙티브 C++ 5,6 장 스터디이펙티브 C++ 5,6 장 스터디
이펙티브 C++ 5,6 장 스터디
quxn6
 
Effective c++ Chapter1,2
Effective c++ Chapter1,2Effective c++ Chapter1,2
Effective c++ Chapter1,2문익 장
 
Python module
Python modulePython module
Python module
건희 김
 
Java 강의자료 ed11
Java 강의자료 ed11Java 강의자료 ed11
Java 강의자료 ed11
hungrok
 
(자바교육/스프링교육/스프링프레임워크교육/마이바티스교육추천)#2.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)
(자바교육/스프링교육/스프링프레임워크교육/마이바티스교육추천)#2.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)(자바교육/스프링교육/스프링프레임워크교육/마이바티스교육추천)#2.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)
(자바교육/스프링교육/스프링프레임워크교육/마이바티스교육추천)#2.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)
탑크리에듀(구로디지털단지역3번출구 2분거리)
 
JavaEE6 - 설계 차원의 단순성
JavaEE6 - 설계 차원의 단순성JavaEE6 - 설계 차원의 단순성
JavaEE6 - 설계 차원의 단순성
Jay Lee
 
토비의 스프링 - DI
토비의 스프링 - DI토비의 스프링 - DI
토비의 스프링 - DI
JU Chae
 
복잡한 오브젝트를 우아하게 처리하기
복잡한 오브젝트를 우아하게 처리하기복잡한 오브젝트를 우아하게 처리하기
복잡한 오브젝트를 우아하게 처리하기
jgyuity1289
 

Similar to Effective java 1 and 2 (12)

결합도 관점에서 본 VO 문제점
결합도 관점에서 본 VO 문제점결합도 관점에서 본 VO 문제점
결합도 관점에서 본 VO 문제점
 
이펙티브 C++ 5,6 장 스터디
이펙티브 C++ 5,6 장 스터디이펙티브 C++ 5,6 장 스터디
이펙티브 C++ 5,6 장 스터디
 
Effective c++ Chapter1,2
Effective c++ Chapter1,2Effective c++ Chapter1,2
Effective c++ Chapter1,2
 
Python module
Python modulePython module
Python module
 
MEC++ 1, 2
MEC++ 1, 2MEC++ 1, 2
MEC++ 1, 2
 
EC 789
EC 789EC 789
EC 789
 
Java 강의자료 ed11
Java 강의자료 ed11Java 강의자료 ed11
Java 강의자료 ed11
 
MEC++ 5
MEC++ 5MEC++ 5
MEC++ 5
 
(자바교육/스프링교육/스프링프레임워크교육/마이바티스교육추천)#2.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)
(자바교육/스프링교육/스프링프레임워크교육/마이바티스교육추천)#2.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)(자바교육/스프링교육/스프링프레임워크교육/마이바티스교육추천)#2.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)
(자바교육/스프링교육/스프링프레임워크교육/마이바티스교육추천)#2.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)
 
JavaEE6 - 설계 차원의 단순성
JavaEE6 - 설계 차원의 단순성JavaEE6 - 설계 차원의 단순성
JavaEE6 - 설계 차원의 단순성
 
토비의 스프링 - DI
토비의 스프링 - DI토비의 스프링 - DI
토비의 스프링 - DI
 
복잡한 오브젝트를 우아하게 처리하기
복잡한 오브젝트를 우아하게 처리하기복잡한 오브젝트를 우아하게 처리하기
복잡한 오브젝트를 우아하게 처리하기
 

More from 중선 곽

자바로 배우는 자료구조
자바로 배우는 자료구조자바로 배우는 자료구조
자바로 배우는 자료구조
중선 곽
 
오픈소스 프레임워크 기반 웹 서비스 설계 (Example)
오픈소스 프레임워크 기반 웹 서비스 설계 (Example)오픈소스 프레임워크 기반 웹 서비스 설계 (Example)
오픈소스 프레임워크 기반 웹 서비스 설계 (Example)
중선 곽
 
프로그래밍 방식의 변천 과정
프로그래밍 방식의 변천 과정프로그래밍 방식의 변천 과정
프로그래밍 방식의 변천 과정
중선 곽
 
젠킨스 설치 및 설정
젠킨스 설치 및 설정젠킨스 설치 및 설정
젠킨스 설치 및 설정
중선 곽
 
지속적인 통합
지속적인 통합지속적인 통합
지속적인 통합
중선 곽
 
Test driven development short lesson
Test driven development   short lessonTest driven development   short lesson
Test driven development short lesson
중선 곽
 
Tomcat monitoring using_javamelody
Tomcat monitoring using_javamelodyTomcat monitoring using_javamelody
Tomcat monitoring using_javamelody
중선 곽
 
Web service performance_test_using_jmeter_ver1.2
Web service performance_test_using_jmeter_ver1.2Web service performance_test_using_jmeter_ver1.2
Web service performance_test_using_jmeter_ver1.2
중선 곽
 
Online service 계층별 성능 모니터링 방안
Online service 계층별 성능 모니터링 방안Online service 계층별 성능 모니터링 방안
Online service 계층별 성능 모니터링 방안
중선 곽
 
Intranet query tuning (example)
Intranet query tuning (example)Intranet query tuning (example)
Intranet query tuning (example)
중선 곽
 
Db 진단 및 튜닝 보고 (example)
Db 진단 및 튜닝 보고 (example)Db 진단 및 튜닝 보고 (example)
Db 진단 및 튜닝 보고 (example)
중선 곽
 
Scale up and scale out
Scale up and scale outScale up and scale out
Scale up and scale out
중선 곽
 
Java rmi 개발 가이드
Java rmi 개발 가이드Java rmi 개발 가이드
Java rmi 개발 가이드
중선 곽
 
Java rmi 개발 가이드
Java rmi 개발 가이드Java rmi 개발 가이드
Java rmi 개발 가이드중선 곽
 
컴퓨터 네트워크와 인터넷
컴퓨터 네트워크와 인터넷컴퓨터 네트워크와 인터넷
컴퓨터 네트워크와 인터넷
중선 곽
 
자바 직렬화 (Java serialization)
자바 직렬화 (Java serialization)자바 직렬화 (Java serialization)
자바 직렬화 (Java serialization)
중선 곽
 
숫자 구분자 처리 (Digit group separators)
숫자 구분자 처리 (Digit group separators)숫자 구분자 처리 (Digit group separators)
숫자 구분자 처리 (Digit group separators)
중선 곽
 
서버 아키텍쳐 입문
서버 아키텍쳐 입문서버 아키텍쳐 입문
서버 아키텍쳐 입문
중선 곽
 
서버 아키텍쳐 입문
서버 아키텍쳐 입문서버 아키텍쳐 입문
서버 아키텍쳐 입문중선 곽
 
서버 성능에 대한 정의와 이해
서버 성능에 대한 정의와 이해서버 성능에 대한 정의와 이해
서버 성능에 대한 정의와 이해
중선 곽
 

More from 중선 곽 (20)

자바로 배우는 자료구조
자바로 배우는 자료구조자바로 배우는 자료구조
자바로 배우는 자료구조
 
오픈소스 프레임워크 기반 웹 서비스 설계 (Example)
오픈소스 프레임워크 기반 웹 서비스 설계 (Example)오픈소스 프레임워크 기반 웹 서비스 설계 (Example)
오픈소스 프레임워크 기반 웹 서비스 설계 (Example)
 
프로그래밍 방식의 변천 과정
프로그래밍 방식의 변천 과정프로그래밍 방식의 변천 과정
프로그래밍 방식의 변천 과정
 
젠킨스 설치 및 설정
젠킨스 설치 및 설정젠킨스 설치 및 설정
젠킨스 설치 및 설정
 
지속적인 통합
지속적인 통합지속적인 통합
지속적인 통합
 
Test driven development short lesson
Test driven development   short lessonTest driven development   short lesson
Test driven development short lesson
 
Tomcat monitoring using_javamelody
Tomcat monitoring using_javamelodyTomcat monitoring using_javamelody
Tomcat monitoring using_javamelody
 
Web service performance_test_using_jmeter_ver1.2
Web service performance_test_using_jmeter_ver1.2Web service performance_test_using_jmeter_ver1.2
Web service performance_test_using_jmeter_ver1.2
 
Online service 계층별 성능 모니터링 방안
Online service 계층별 성능 모니터링 방안Online service 계층별 성능 모니터링 방안
Online service 계층별 성능 모니터링 방안
 
Intranet query tuning (example)
Intranet query tuning (example)Intranet query tuning (example)
Intranet query tuning (example)
 
Db 진단 및 튜닝 보고 (example)
Db 진단 및 튜닝 보고 (example)Db 진단 및 튜닝 보고 (example)
Db 진단 및 튜닝 보고 (example)
 
Scale up and scale out
Scale up and scale outScale up and scale out
Scale up and scale out
 
Java rmi 개발 가이드
Java rmi 개발 가이드Java rmi 개발 가이드
Java rmi 개발 가이드
 
Java rmi 개발 가이드
Java rmi 개발 가이드Java rmi 개발 가이드
Java rmi 개발 가이드
 
컴퓨터 네트워크와 인터넷
컴퓨터 네트워크와 인터넷컴퓨터 네트워크와 인터넷
컴퓨터 네트워크와 인터넷
 
자바 직렬화 (Java serialization)
자바 직렬화 (Java serialization)자바 직렬화 (Java serialization)
자바 직렬화 (Java serialization)
 
숫자 구분자 처리 (Digit group separators)
숫자 구분자 처리 (Digit group separators)숫자 구분자 처리 (Digit group separators)
숫자 구분자 처리 (Digit group separators)
 
서버 아키텍쳐 입문
서버 아키텍쳐 입문서버 아키텍쳐 입문
서버 아키텍쳐 입문
 
서버 아키텍쳐 입문
서버 아키텍쳐 입문서버 아키텍쳐 입문
서버 아키텍쳐 입문
 
서버 성능에 대한 정의와 이해
서버 성능에 대한 정의와 이해서버 성능에 대한 정의와 이해
서버 성능에 대한 정의와 이해
 

Effective java 1 and 2

  • 1. This report is written by Sunny Kwak. (sunnykwak@hanmail.net, sunnykwak.egloos.com) 2009.07.31 Effective Java [Issue 1 and 2] Version 0.1
  • 2. 1 Effective Java. Issue 1 and 2 Issue 1. 생성자 대신 static 팩토리 메소드 사용을 고려하자. 객체는 생성자 함수만이 만들 수 있는 게 아니다! public Boolean(boolean value ) { this.value = value; } public static Boolean valueOf(boolean b ) { return b ? Boolean.TRUE :Boolean.FALSE; } java API에 포함된 Boolean 클래스는 생성자(Constructor) 도 제공하지만, 가급적 valueOf() 정적 메소드 사용을 권장하고 있다. 결과는 똑같아 보이지만, valueOf() 메소드를 사용하면 인스턴스 생성이 억제 된다. (자원 젃약 효과) VS.
  • 3. 2 Effective Java. Issue 1 and 2 Issue 1. 생성자 대신 static 팩토리 메소드 사용을 고려하자 1. 생성자 함수와 달리 팩토리 메소드는 클래스와 다른 명칭을 가질 수 있다. - BigInteger 클래스의 소수(素數) 인스턴스를 반홖하는 메소드의 명칭은 BigInteger.probalePrime() 이며, 생성자의 특징을 명확히 드러낸다. - 생성자가 여러 개 필요할 경우, 각각의 용도에 맞는 이름을 부여할 수 있다. 2. 호출 될 때마다 새로운 객체를 생성할 수도 있고, 이미 생성된 객체를 반홖 할 수 도 있다. - 인스턴스 생성을 제어할 수 있으므로, 자원을 좀 더 효율적으로 관리할 수 있게 된다. - 싱글톤(singleton) 또는 인스턴스 생성 불가(noninstantiable) 클래스를 만들 수 있다. 3. 자신이 반홖하는 타입의 하위 타입(sub type) 객체도 반홖할 수 있다. - 생성자 함수는 자싞이 속한 클래스의 인스턴스만을 만들 수 있지만, Static Factory는 유연하게 하위 클래스의 객체를 생성하고 반홖할 수 있다. 4. 매개변수화 타입(parameterized type) 인스턴스를 생성하는 코드를 간결하게 해준다. public static <K, V> HashMap <K, V> newInstance() { return new HashMap<K, V>(); } Static Factory 메소드의 장점
  • 4. 3 Effective Java. Issue 1 and 2 Issue 1. 생성자 대신 static 팩토리 메소드 사용을 고려하자 1. 인스턴스 생성을 위한 public/protected 생성자를 선언하지 않고 static factory 메소드만 가지고 있는 클래스는 하위 클래스를 만들 수 없다. - 장점일 수도 있도, 단점이 될 수도 있다. 2. 다른 static 메소드와 구분하기 어렵다. - 다른 메소드와 섞여 있으면, 용도를 알아차리기 어렵기 때문에, 문서화에 싞경 써야 한다. Static Factory 메소드의 단점
  • 5. 4 Effective Java. Issue 1 and 2 Issue 2. 생성자의 매개 변수가 많을 때는 빌더(builder)를고려하자 매개 변수가 많은 생성자의 문제? ‘식품 영양 정보’를 나타내는 데이터 클래스를 예로 들어보자. 다양한 필수, 선택 항목을 포함할 수 있다. 필수 항목 : 식품의 용량, 개수, 칼로리 선택 항목 : 총 지방 함량, 포화 지방, 트랜스 지방, 콜레스테롤, 나트륨, 단백질, 탄수화물, 비타민… 등 수십개 항목 1. 인스턴스 생성 시에 초기화 해야 하는 항목 수가 많고… 2. 필수/선택 매개변수들을 초기화할 수 있는 다양한 생성자 함수를 선얶해야 한다. 3. 일반적으로, 텔리스코핑(telescoping) 생성자 패턴을 사용한다. NutritionFacts cola = new NutritionFacts( 240, 8, 120, 10, 26, 27 ); 위와 같은 코드는 가독성이 현저히 떨어진다. 즉, 이해하기 어렵다. 각각의 파라미터가 어떤 필드를 설정하는지…? NutritionFacts +servingSize +servings +calories +fat +sodium +carbohydrate +protein +NutritionFatcs(int servingSize, int serviings) +NutritionFacts(int servingSize, int servings, int calories)
  • 6. 5 Effective Java. Issue 1 and 2 Issue 2. 생성자의 매개 변수가 많을 때는 빌더(builder)를고려하자 대안~?자바빈즈 패턴 매개 변수가 없는 객체를 생성한 후 setter 메소드를 호출해서 각각의 필드 값을 초기화 한다. NutritionFacts cola = new NutritionFacts(); cola.setServingSize(240); cola.setServings(8); cola.setCalories(80); cola.setSodium(35); 한 시젃 유행(?)하던 기법이지만, 생성 과정에서 불완젂한 상태에 놓여 있게 된다. 불변(immutable) 클래스를 만들 수도 없다.
  • 7. 6 Effective Java. Issue 1 and 2 Issue 2. 생성자의 매개 변수가 많을 때는 빌더(builder)를고려하자 확실한 대안~! 빌더 패턴 (Builder pattern) 빌더(builder) 클래스는 자싞이 생성하는 객체의 클래스에 포함된 static 멤버 클래스. NutritionFacts +servingSize +servings +calories +fat +sodium +carbohydrate +protein +private NutritionFatcs(Builder builder) Builder +servingSize +servings +calories +fat +carbohydrate +sodium +Builder(int savingSize, int servings) +Builder calories(int val) +Builder fat(int val) +NutritionFacts build() NutritionFacts cola = new NutritionFacts.Builder(240,8). calories(100).sodium(35).carbohydrate(27).build(); 코드 작성이 쉽고, 이해하기 쉽다. 다만, 코드 분량이 증가하는 단점이 있다.