데이터가 아닌 책임에 초점을 맞춰야 한다.
이 객체가 포함해야 하는 데이터가 무엇인가?
데이터를 처리하는데 필요한 오퍼레이션이 무엇인가?
이 객체가 수행해야하는 책임이 무엇인가?
이 책임을 수행하는 데 필요한 데이터는 무엇인가?
🧐 객체의 책임은 어떻게 할당해야 할까?
이 방법을 객체 책임의 평가 기준으로부터 확인할 수 있다.
메시지를 전송해야 하는데 누구에게 전송하지?
- 책임 주도 설계의 흐름 (3장)
- 시스템이 사용자에게 제공해야 하는 기능인 시스템 책임을 파악한다.
- 시스템 책임을 더 작은 책임으로 분할한다.
- 분할된 책임을 수행할 수 있는 적절한 객체 또는 역할을 찾아 책임을 할당한다.
- 객체가 책임을 수행하는 도중 다른 객체의 도움이 필요한 경우 이를 책임질 적절한 객체 또는 역할을 찾는다.
- 해당 객체 또는 역할에게 책임을 할당함으로써 두 객체가 협력하게 한다.
General Responsibility Assignment Software Pattern
1. 하나의 영화는 여러번 상영될 수 있으며, 하나의 상영은 여러변 예약될 수 있다는 것을 보여준다.
2. 영화는 다수의 할인 조건을 가질 수 있으며,
할인 조건에는 순번 조건과 기간 조건이 존재한다는 사실이 표현되어 있다.
3. 할인 조건은 순번 조건과 기간 조건으로 분류되고 영화는 금액이나 비율에 따라 할인될 수 있지만,
동시에 두 가지 할인 조건을 적용할 수 없다는 사실이 표현되어 있다.
올바른 모델이란 존재하지 않는다.
- 2장에서 설정한 도메인에서는, 할인 정책이라는 개념이 독립적인 개념으로 분리되어 있었지만, 현재 도메인에서는 영화의 종류로 표현되어 있다.
- 어느 쪽이 올바른 도메인인가?
- 두 도메인 모두 올바른 구현을 이끌어낼 수 있다면 정답은 '둘 다'이다.
- 올바른 도메인은 존재하지 않는다.
- 필요한 것은 도메인을 그대로 투영한 모델이 아니라, 구현에 도움이 되는 모델. 다시 말해 실용적이면서도 유용한 모델이다.
책임을 App에 전송된 메시지로 간주하고, 이 메시지를 책임질 첫 번째 객체를 선택하는 것으로 설계를 시작한다.
예매하라
Screening
정보 전문가 패턴(INFORMATION EXPERT)
- 책임을 수행하는 데 필요한 정보를 가지고 있는 객체에게 책임을 할당하는 패턴.
- 객체가 자신이 소유하고 있는 정보와 관련된 작업을 수행한다는 일반적인 직관을 표현
- 정보를 알고 있는 객체만이 책임을 어떻게 수행할지 결정할 수 있다.
- 정보와 행동을 최대한 가까운 곳에 위치시켜 캡슐화를 유지할 수 있다.
- 필요한 정보를 가진 객체들로 책임이 분산되므로, 더 응집력있고 이해하기 쉬워진다.
- 따라서 높은 응집도가 가능하다.
- 결합도가 낮아져, 간결하고 유지보수 하기 쉬운 시스템을 구축할 수 있다.
예매하라
라는 메시지를 수신했을 때, Screening
이 수행해야 하는 작업의 흐름을 생각해본다.예약하라
라는 메시지를 완료하기 위해, 예매 금액을 계산하는 작업이 필요하다.
예매 금액은 영화 한 편의 가격에 예매 인원수를 곱한 값으로 구할 수 있다. Screening
은 영화 한편의 가격을 알지 못하므로, 필요한 정보를 알고 있는 외부 객체에게 도움을 요청해 가격을 얻어야 한다.
Screening
은 무엇을 원하는가?가격을 계산하라
Movie
Movie
이다.할인 조건에 따라 영화가 할인 가능한지 판단
하는 작업은 Movie
가 수행할 수 없다.할인 조건(DiscountCondition)
이다.DiscountCondition
은 할인 여부 판단에 필요한 모든 정보를 알고 있으므로, 외부 도움 없이도 스스로 할인 여부를 판단할 수 있다.DiscountCondition
은 외부에 메시지를 전송하지 않는다.수많은 설계 선택지 중, 무엇을 기준으로 선택해야 할까? 높은 응집도와 낮은 결합도를가지는 설계를 선택해라.
설계는 트레이드 오프다.
동일한 기능을 구현할 수 있는 무수히 많은 설계 중, 하나를 선택해야 하는 경우가 빈번하다. 이 경우에는 올바른 책임 할당을 위해 INFORMATION EXPERT(정보 전문가) 패턴 이외에도 다른 책임 할당 패턴을 함께 고려할 필요가 있다.
위의 그림과 같이, Moive
가 DiscountCondition
에게 할인금액을 요구하지 않고, Screening
이 직접 DiscountCondition
에게 할인 금액을 요구하도록 설계할 수도 있다.
기능 적인 측면에서는 두 설계에서 차이가 없는 상황에서, 왜 이 설계 대신 Movie
가 DisocuntCondition
과 협력하는 방법을 선택한 것일까?
그 이유는 응집도와 결합도다.
높은 응집도와 낮은 결합도는 책임 할당 시 항상 고려되어야 하는 기본 원리이다. 책임 할당의 다양한 설계 선택지 중, 응집도와 결합도 측면에서 더 나은 대안을 선택하는 것이 좋다.
GRASP에서는 이를 LOW COUPLING(낮은 결합도) 패턴과 HIGH COHESIONG(높은 응집도) 패턴이라고 부른다.
LOW COUPLING 패턴
- 설계의 전체적인 결합도가 낮도록 설계해라.
- 의존성을 낮추고, 변화의 영향을 줄이며, 재사용성을 증가시킨다.
DiscountCondition
은 Movie
와 협력하는 것이 좋을까, 아니면 Screening
과 협력하는 것이 좋을까?Movie
와 DiscountCondition
은 이미 결합되어 있어, 둘 간의 협력은 설계 전체적으로 결합도를 추가하지 않는다.Screening
이 DiscountCondition
과 협력하는 경우, 새로운 결합도가 추가된다.Movie
와 협력하는 것이 더 나은 설계 대안이다.HIGH COHESION 패턴
- 높은 응집도를 유지할 수 있게 책임을 할당해라.
- 복잡성을 관리할 수 있는 수준으로 유지할 수 있다.
Screening
의 가장 큰 책임은 예매를 생성하는 것이다.Screening
이 DiscountCondition
과 협력해야 한다면, Screening
은 영화 요금 계산과 관련된 책임 일부를 떠안게 된다.Screening
은 아래 정보를 모두 알고 있어야 한다.DiscountCondition
이 할인 여부를 판단할 수 있다는 사실.Movie
가 할인 여부를 필요로 한다는 사실Screening
도 함께 변경되어야 한다.Screening
과 DiscountCondition
이 협력하면, Screening
은 서로 다른 이유로 변경되어야 하는 책임을 짊어지게 되므로, 응집도가 낮아질 수 밖에 없다.Movie
의 주된 책임은 영화 요금을 계산하는 것이다.Movie
와 DiscountCondition
의 협력은 전체 설계의 응집도에 아무런 해도 끼치지 않는다.Reservation
인스턴스Reservation
인스턴스 생성의 책임을 할당해야 함을 의미한다.Reservation
의 창조자public class Screening {
public Reservation reserve(Customer customer, int audienceCount) {}
}
whenScreened
)sequence
)movie
) private Movie movie;
private int sequence;
private LocalDateTime whenScreened;
Movie
에 전송하는 메서드 시그니처가 calcualteMovieFee(Screening screening)
임에 주목하자.Movie
가 아니라, 송신자인 Screening
의 의도를 표현했다.Screening
이 Movie
의 구현을 고려하지 않고 필요한 메시지를 결정함으로써, Movie
의 내부 구현을 깔끔하게 캡슐화했다는 점이다. public Money calculateFee(int audienceCount) {
return movie.calculateMovieFee(this).times(audienceCount);
}
public class Screening {
private Movie movie;
private int sequence;
private LocalDateTime whenScreened;
public Reservation reserve(Customer customer, int audienceCount) {
return new Reservation(customer, this.calculateFee(audienceCount), audienceCount);
}
public Money calculateFee(int audienceCount) {
return movie.calculateMovieFee(this).times(audienceCount);
}
}
public class Movie {
public Money calculateMovieFee(Screening screening) {}
}
private String title;
private Duration runningTime;
private Money fee;
private List<DiscountCondition> discountConditions;
private MovieType movieType;
private Money discountAmount;
private Doublie discountPercent;
enum MovieType {
AMOUNT_DISCOUNT, // 금액 할인 정책
PERCENT_DISCOUNT, // 비율 할인 정책
NONE_DISCOUNT; // 미적용
}
public Money calculateMovieFee(Screening screening) {
if(isDiscountable(screening)) {
return fee.minus(calculateDiscountAmount());
}
return fee;
}
public boolean isDiscountable(Screening screening) {
return discountConditions.stream()
.anyMatch(condition -> condition.isSatisfiedBy(screening));
}
calculateDiscountAmoun
private Money calculateDiscountAmount() {
switch(movieType) {
case AMOUNT_DISCOUNT:
return calculateAmountDiscountAmount();
case PERCENT_DISCOUNT:
return calculatePercentDiscountAmount();
case NONE_DISCOUNT:
return calculateNoneDiscountAmount();
}
throw new IllegalStateException();
}
public Money calculateAmountDiscountAmount() {
return discountAmount;
}
public Money calculatePercentDiscountAmount() {
return fee.minus(discountAmount);
}
public Money calculateNoneDiscountAmount() {
return Money.ZERO;
}
public class Movie {
private String title;
private Duration runningTime;
private Money fee;
private List<DiscountCondition> discountConditions;
private MovieType movieType;
private Money discountAmount;
private Doublie discountPercent;
public Money calculateMovieFee(Screening screening) {
if(isDiscountable(screening)) {
return fee.minus(calculateDiscountAmount());
}
return fee;
}
public boolean isDiscountable(Screening screening) {
return discountConditions.stream()
.anyMatch(condition -> condition.isSatisfiedBy(screening));
}
private Money calculateDiscountAmount() {
switch(movieType) {
case AMOUNT_DISCOUNT:
return calculateAmountDiscountAmount();
case PERCENT_DISCOUNT:
return calculatePercentDiscountAmount();
case NONE_DISCOUNT:
return calculateNoneDiscountAmount();
}
throw new IllegalStateException();
}
public Money calculateAmountDiscountAmount() {
return discountAmount;
}
public Money calculatePercentDiscountAmount() {
return fee.minus(discountAmount);
}
public Money calculateNoneDiscountAmount() {
return Money.ZERO;
}
}
enum MovieType {
AMOUNT_DISCOUNT, // 금액 할인 정책
PERCENT_DISCOUNT, // 비율 할인 정책
NONE_DISCOUNT; // 미적용
}
할인 여부를 판단하라
public class DiscountCondition {
public boolean isSatisfiedBy(Screening screening) {}
}
public enum DiscountConditionType {
SEQUENCE, // 순번 조건
PERIOD // 기간 조건
;
}
public class DiscountCondition {
private DiscountConditionType type;
private int sequence;
private DayOfWeek dayOfWeek;
private LocalTime startTime;
private LocalTime endTime;
public boolean isSatisfiedBy(Screening screening) {
if (type == DiscountConditionType.PERIOD) {
return isSatisfiedByPeriod(screening);
}
return isSatisfiedSequence(screening);
}
private boolean isSatisfiedByPeriod(Screening screening) {
return dayOfWeek.equals(screening.getWhenScreened().getDayOfWeek()) &&
startTime.compareTo(screening.getWhenScreened().toLocalTime()) <= 0 &&
endTime.isAfter(screening.getWhenScreened().toLocalTime()) >= 0;
}
private boolean isSatisfiedSequence(Screening screening) {
return sequence == screening.getSequence();
}
}
public LocalDateTime getWhenScreened() {
return whenScreened;
}
public int getSequence() {
return sequence;
}
DiscountCondition
- 변경이유 1; 새로운 할인 조건 추가
- `isSatisfiedBy`의 `if ~ else`구문 수정 필요
- `DiscountCondition`에 새로운 할인조건에 필요한 조건 속성을 추가.
- 변경이유2; 순번 조건을 판단하는 로직 변경
- `isSatisfiedBySequence` 내부 구현 수정
- 순번 조건에 요구되는 데이터인 `sequence` 속성 변경.
- 변경이유3; 기간 조건을 판단하는 로직이 변경되는 경우
- `isSatisfiedBySequence` 내부 구현 수정
- 순번 조건을 판단하는데 필요한 데이터 변경 필요.
📌 클래스의 응집도 파악
다음은 낮은 응집도를 가지는 클래스의 징후들이다.
대부분 아래 세 가지 문제를 동시에 가진다.
- 클래스가 하나 이상의 이유로 변경돼야 하는 경우
- 변경 이유를 기준으로 클래스 분리
- 클래스의 인스턴스 초기화 시점에, 서로 다른 속성 혹은 일부의 속성을 초기화
- 초기화되는 속성의 그룹을 기준으로 클래스 분리
- 메서드 그룹이 속성 그룹을 사용하는지 여부로 그룹화
- 그룹을 기준으로 클래스 분리
public class PeriodCondition {
private DayOfWeek dayOfWeek;
private LocalTime startTime;
private LocalTime endTime;
public PeriodCondition(DayOfWeek dayOfWeek, LocalTime startTime, LocalTime endTime) {
this.dayOfWeek = dayOfWeek;
this.startTime = startTime;
this.endTime = endTime;
}
public boolean isSatisfiedBy(Screening screening) {
return dayOfWeek.equals(screening.getWhenScreened().getDayOfWeek()) &&
startTime.compareTo(screening.getWhenScreened().toLocalTime()) <= 0 &&
endTime.isAfter(screening.getWhenScreened().toLocalTime()) >= 0;
}
}
public class SequenceCondition {
private int sequence;
public SequenceCondition(int sequence) {
this.sequence = sequence;
}
public boolean isSatisfiedBy(Screening screening) {
return sequence == screening.getSequence();
}
}
Movie
와 협력하는 클래스가 DiscountCondition
하나에서 PeriodCondition
, SequenceCondition
2개로 늘어났다.Movie
안에서 두 클래스의 목록을 따로 유지할 수 있다.Movie
가 PeriodCondition
과 SequenceCondition
양쪽 모두에 결합되어야 한다.List
추가, isDiscountable
메서드에 추가, 할인조건판단 로직 추가가 필요해짐.public class Movie {
private List<PeriodCondition> periodConditions;
private List<SequenceCondition> sequenceConditions;
private boolean isDiscountable(Screening screening) {
return checkPeriodConditions(screening) || checkSequenceConditions(screening);
}
private boolean checkPeriodConditions(Screening screening) {
return periodConditions.stream()
.anyMatch(condition -> condition.isSatisfiedBy(screening));
}
private boolean checkSequenceConditions(Screening screening) {
return sequenceConditions.stream()
.anyMatch(condition -> condition.isSatisfiedBy(screening));
}
}
DiscountCondition
내부만 수정하면 됐지만, 이제는 Movie
에도 변경의 영향을 미치고있다.DiscountCondition
입장에서는 응집도가 향상했지만, 변경과 캡슐화라는 관점에서 전체적으로 설계의 품질이 나빠졌다.Movie
입장에서는, PeriodCondition
과 SequenceCondition
은 아무 차이가 없다.Movie
는 몰라도 괜찮다.Movie
입장에서 둘은 동일한 역할을 수행하고 있다.public interface DiscountCondition {
boolean isSatisfiedBy(Screening screening);
}
public class PeriodCondition implements DiscountCondition {
...
}
public class SequenceCondition implements DiscountCondition {
...
}
public class Movie {
private List<DiscountCondition> discountConditions;
public Money calculateMovieFee(Screening screening) {
if (isDiscountable(screening)) {
return fee.minus(calculateDiscountAmount());
}
}
return fee;
}
Movie
와 DiscountCondition
사이의 협력은 다형적이다.POLYMORPHISM(다형성) 패턴
- 객체의 타입에 따라 변하는 로직이 있을 때, 변하는 로직을 담당할 책임을 어떻게 할당해야 할까?
- 타입을 명시적으로 정의하고, 각 타입에 다형적으로 행동하는 책임을 할당해라.
- 조건에 따른 변화는 프로그램의 기본 논리다.
if ~ else
,switch ~ case
등 조건 논리를 이용해 설계한다면, 변화 시 조건 논리를 수정해야 한다.
- 이는 수정이 어렵고 변경에 취약하게 만든다.
- 조건적 논리를 이용하는 대신, POLYMORPHISM(다형성)을 이용해 새로운 변화를 다루기 쉽게 확장할 수 있다.
DiscountCondition
이라는 추상화가 구체적인 구현을 캡슐화하고 있다.Movie
는 영향을 받지 않음을 의미한다. PROTECTED VARIATIONS(변경 보호) 패턴
- 객체, 서브시스템, 그리고 시스템을 어떻게 설계해야 변화와 불안정성이 다른 요소에 나쁜 영향을 미치지 않도록 방지할 수 있을까?
- 변화가 예상되는 불안정한 지점을 식별하고, 그 주위에 안정된 인터페이스를 형성하도록 책임을 할당해라.
- 설계에서 변하는 것이 무엇인지 고려하고 변하는 개념을 캡슐화하라.
Movie
역시 두가지 타입을 하나의 클래스 안에서 구현해, 여러개의 변경 이유를 가진다.Screening
과 Movie
가 메시지를 통해서만 다형적으로 협력하므로, 변화의 전파를 막을 수 있었다.calculateDiscountAmount
메서드를 추상 메서드로 선언해, 서브 클래스들이 할인 금액을 오버라이딩하도록 한다.public class Movie {
private String title;
private Duration runningTime;
private Money fee;
private List<DiscountCondition> discountConditions;
public Money calculateMovieFee(Screening screening) {
if(isDiscountable(screening)) {
return fee.minus(calculateDiscountAmount());
}
return fee;
}
public boolean isDiscountable(Screening screening) {
return discountConditions.stream()
.anyMatch(condition -> condition.isSatisfiedBy(screening));
}
abstract protected Money calculateDiscountAmount();
}
Movie
를 상속받아 구현을 재활용한다.public class AmountDiscountMovie extends Movie {
private Money discountAmount;
public AmountDiscountMovie(
String title,
Duration runningTime,
Money fee,
Money discountAmount,
DiscountCondition... discountConditions) {
super(title, runningTime, fee, discountConditions);
this.discountAmount = discountAmount;
}
@Override
protected Money calculateDiscountAmount() {
return discountAmount;
}
}
Movie
를 상속받아 구현을 재활용한다.public class PercentDiscountMovie extends Movie{
private double percent;
public PercentDiscountMovie(
String title,
Duration runningTime,
Money fee,
double percent,
DiscountCondition... discountConditions) {
super(title, runningTime, fee, discountConditions);
this.percent = percent;
}
@Override
protected Money calculateDiscountAmount() {
return getFee().times(percent);
}
}
protected
로 설정한다.public abstract class Movie {
protected Money getFee() {
return fee;
}
}
Movie
를 상속받아 구현을 재활용한다.public class NoneDiscountAmount extends Movie{
public NoneDiscountAmount(
String title,
Duration runningTime,
Money fee) {
super(title, runningTime, fee, discountConditions);
}
@Override
protected Money calculateDiscountAmount() {
return Money.ZERO;
}
}
도메인의 구조가 코드의 구조를 이끈다.
- 최종 설계된 클래스의 구조가 초기 도메인 모델의 구조와 유사하다.
- 도메인 모델은 설계에 필요한 용어를 제공할 뿐만 아니라, 코드의 구조에도 영향을 미친다.
- 구현을 가이드할 수 있는 도메인 모델을 선택해라.
- 객체지향은 도메인의 개념과 구조를 반영한 코드를 가능하게 만들기 때문에, 도메인 구조가 코드의 구조를 이끌어 내는 것은 자연스럽고 바람직한 것이다.
1번이 더 좋은 선택이지만, 유사한 변경이 반복적으로 발생한다면 복잡성이 상승하더라도 2번을 선택해 유연성을 추가할 수 있다.
Movie
클래스를 상속 받아 각각의 할인 정책을 구현하고 있다.Movie
의 하위클래스로 고정되어, 할인 정책 변경 시 새로운 Movie
객체를 생성해야 한다.할인 정책 변경 시, 새로운 인스턴스를 생성하고, 상태를 복사하고, 식별자를 관리하는 코드를 추가해야 한다. 이는 복잡하고 오류 발생 가능성이 높은 과정이다.
Movie movie = new AmountDiscountMoive("타이타닉", 10000, 1000);
// 할인 정책을 변경하려면 새로운 객체를 생성해야 함
movie = new PercentDiscountMovie("타이타닉", 1000, 0.1));
할인 정책 변경이 빈번하게 발생하는 경우, 이를 수용하기 힘든 상속 대신, 복잡성이 증가하더라도 변경에 유연한 합성을 사용할 수 있다.
Movie
클래스가 DiscountPolicy
인터페이스를 참조한다.할인 정책 변경이 분리되어, 단순히 Movie
의 DiscountPolciy
의 인스턴스를 교체함으로써 할인 정책 변경을 구현할 수 있다.
Movie movie = new Movie("타이타닉", 10000, new AmountDiscountPolicy(1000));
// 나중에 할인 정책을 변경하고 싶다면
movie.changeDiscountPolicy(new PercentDiscountPolicy(0.1));
코드의 구조가 도메인의 구조에 대한 새로운 통찰력을 제공한다.
코드 구조의 변경은 곧 도메인에 대한 관점의 변화를 의미한다.
할인 정책의 자유로운 변경은, 도메인에 포함된 주요한 요구사항이다. 이 요구사항을 수용하기 위해 할인 정책이라는 개념을 코드 상에 명시적으로 드러냈다면, 도메인 모델 역시 코드의 관점에 따라 바뀌어야 한다.
도메인 모델은 구현과 밀접한 관계를 맺어야 한다. 도메인 모델은 코드에 대한 가이드를 제공해야 하며, 코드의 변화에 발맞춰 함께 변화해야 한다.
책임 주도 설계에 따라, 데이터가 아닌 책임 관점에서 설계를 고안하는 것은 어려운 작업이다. 이런 경우, 최대한 빠르게 목적한 기능을 수행하는 코드를 작성하고, 리팩터링하는 과정에서 좋은 설계를 얻을 수 있다.
객체 디자인에서 가장 기본이 되는 것 중의 하나(원칙은 아닐지라도)는 책임을 어디에 둘지를 결정하는 것이다. 나는 십년 이상 객체를 가지고 일했지만, 처음 시작할 때는 여전히 적당한 위치를 찾지 못한다. 늘 이런 점이 나를 괴롭혔지만, 이제는 이런 경우에 리팩터링을 사용하면 된다는 것을 알게 되었다.[Fowler 1999a]
ReservationAgency
에 집중되어 있었다.ReservationAgency
의 로직들을 적절한 객체의 책임으로 분배하면, 책임 주도 설계와 유사한 결과를 얻을 수 있다.public class ReservationAgency {
public Reservation reserve(Screening screening, Customer customer, int audienceCount) {
Movie movie = screening.getMovie();
boolean discountable = false;
for(DiscountCondition condition : movie.getDiscountConditions()) {
if (condition.getType() == DiscountConditionType.PERIOD) {
discountable = screening.getWhenScreened().getDayOfWeek().equals(condition.getDayOfWeek())
&& condition.getStartTime().compareTo(screening.getWhenScreened().toLocalTime()) <= 0
&& condition.getEndTime().compareTo(screening.getWhenScreened().toLocalTime()) >= 0;
} else {
discountable = condition.getSequence() == screening.getSequence();
}
if(discountable) {
break;
}
}
Money fee;
if (discountable) {
Money discountAmount = Money.ZERO;
switch(movie.getMovieType()) {
case AMOUNT_DISCOUNT:
discountAmount = movie.getDiscountAmount();
break;
case PERCENT_DISCOUNT:
discountAmount = movie.getFee().times(movie.getDiscountPercent());
break;
case NONE_DISCOUNT:
discountAmount = Money.ZERO;
break;
}
fee = movie.getFee().minus(discountAMount).times(AudienceCount);
} else {
fee = movie.getFee();
}
return new Reservation(customer, screening, fee, audienceCount);
}
}
reserve
메서드는 길이가 너무 길고 이해하기도 힘들다. 이런 메서드는 유지 보수에 부정적인 영향을 미친다. 마이클 패더스(Michael Feathers)는 이런 메서드를 몬스터 메서드(moster method)라고 부른다.
나는 다음과 같은 이유로 짧고, 이해하기 쉬운 이름으로 된 메서드를 좋아한다. 첫째, 메서드가 잘게 나눠져 있을 때 다른 메서드에서 사용될 확률이 높아진다. 둘째, 고수준의 메서드를 볼 때 일련의 주석을 읽는 것 같은 느낌이 들게 할 수 있다. 또한 메서드가 잘게 나눠져 있을 때 오버라이딩하는 것도 훨씬 쉽다. 만약 큰 메서드에 익숙해져 있다면 메서드를 잘게 나누는 데는 약간의 시간이 걸릴 것이다. 작은 메서드는 실제로 이름을 잘 지었을 때만 그 진가가 드러나므로, 이름을 지을 때 주의해야 한다.
사람은 때때로 나에게 한 메서드의 길이가 얼마나 돼야 할지를 묻는다. 그러나 나는 길이가 중요하다고 생각하지 않는다. 중요한 것은 메서드의 이름과 메서드 몸체의 의미적 차이다. 뽑아내는 것이 코드를 더욱 명확하게 하면 새로 마든 메서드의 이름이 원래 코드의 길이보다 길어져도 뽑아낸다.[Fowler99a]
public class ReservationAgencyRefactor {
public Reservation reserve(Screening screening, Customer customer, int audienceCount) {
boolean discountable = checkDiscountable(screening);
Money fee = calculateFee(screening, audienceCount, discountable);
return createReservation(customer, screening, fee, audienceCount);
}
private boolean checkDiscountable(Screening screening) {
return screening.getMovie().getDiscountConditions().stream()
.anyMatch(condition -> isDiscountable(screening, condition));
}
private boolean isDiscountable(Screening screening, DiscountCondition condition) {
if (condition.getType() == DiscountConditionType.PERIOD) {
return isSatisfiedByPeriod(screening, condition);
}
return isSatisfiedBySequence(screening, condition);
}
private boolean isSatisfiedBySequence(Screening screening, DiscountCondition condition) {
return condition.getSequence() == screening.getSequence();
}
private boolean isSatisfiedByPeriod(Screening screening, DiscountCondition condition) {
return screening.getWhenScreened().getDayOfWeek().equals(condition.getDayOfWeek())
&& condition.getStartTime().compareTo(screening.getWhenScreened().toLocalTime()) <= 0
&& condition.getEndTime().compareTo(screening.getWhenScreened().toLocalTime()) >= 0;
}
private Money calculateFee(Screening screening, int audienceCount, boolean discountable) {
if (discountable) {
return screening.getMovie().getFee()
.minus(calculateDiscountedFee(screening.getMovie()))
.times(audienceCount);
}
return screening.getMovie().getFee();
}
private Money calculateDiscountedFee(Movie movie) {
switch(movie.getMovieType()) {
case AMOUNT_DISCOUNT:
return calculateNoneDiscountedFee(movie);
case PERCENT_DISCOUNT:
return calculatePercentDiscountedFee(movie);
case NONE_DISCOUNT:
return calculateAmountDiscountedFee(movie);
}
throw new IllegalArgumentException();
}
private Money calculateNoneDiscountedFee(Movie movie) {
return movie.getFee();
}
private Money calculatePercentDiscountedFee(Movie movie) {
return movie.getFee().times(movie.getDiscountPercent());
}
private Money calculateAmountDiscountedFee(Movie movie) {
return movie.getDiscountAmount();
}
private Reservation createReservation(Screening screening, Customer customer,
int audienceCount, Money fee) {
return new Reservation(customer, screening, fee, audienceCount);
}
}
public
메서드는 상위 수준의 명세를 읽는 것 같은 느낌을 준다. public Reservation reserve(Screening screening, Customer customer, int audienceCount) {
boolean discountable = checkDiscountable(screening);
Money fee = calculateFee(screening, audienceCount, discountable);
return createReservation(customer, screening, fee, audienceCount);
}
ReservationAgency
의 응집도는 여전히 낮다.책임주도 설계 방법에 익숙하지 않다면, 일단 데이터 중심으로 구현한 후에 리팩토링 하더라도 유사한 결과를 얻을 수 있다.