재사용 가능한 코드를 가지고 싶으면 클래스 자체가 자신의 의존성의 인스턴스를 재생산하지 않도록 클래스를 작성해야 한다.
즉 클래스 안에서 클래스 자체의 의존성을 생성하지 않아야 한다.
// bad
export class MessagesService {
messagesRepo : MessagesRepository;
constructor(){
this.messagesRepo = new MessagesRepository();
}
}
// better
export class MessagesServce {
messagesRepo : MessagesRepository;
constructor(repo: MessagesRepository){
this.messagesRepo = repo;
}
}
// good
interface Repository {
findOne(id: string);
findAll();
create(content:string);
}
export class MessagesServices {
messagesRepo : Repository;
constructor(repo: Repository) {
this.messagesRepo = repo
}
}
위의 코드가 있다.
1번 bad 코드의 경우는 MessagesRepository라는 repo를 호출 할 때 즉 MessagesService가 사본을 만들 때 MessagesRepository의 사본도 생성하고 있다.
2번의 better 코드는 자체적인 의존성을 생성하도록 하는 것이 아니라 생성자에 대한 인수로서 의존성을 받도록 설정할 수 있다.
이는 MessagesService가 사본을 만들 때 MessagesRepository의 사본을 생성하는 것이 아니라 이미 존재하는 사본을 제공하는 것이다.
하지만 이는 생성자에 전달되는 MessagesRepository의 사본에 의존하고 있다. 그렇기 때문에 항상 MessagesRepository를 생성해야 한다.
3번 best 코드는 MessagesRepository를 받는 것이 아닌 interface Repository라는 인터페이스로 정의하여 MessagesService를 제공할 때 Repository 인터페이스를 충족하는 객체를 제공해야 한다.