해당 강의를 보고 정리합니다.
class AuthGuard {
async authenticate(userId: string) {
const member = await this.userRepository.findOne({ id: userId });
if (!member) return false;
if (member.getVerificationEmailStatus() !== 2) return false;
const isSamePassword = await isSameAsHash(password, user.password);
if (!isSamePassword) {
return fail;
}
return true;
}
}
class AuthGuard {
async authenticate(userId: string) {
const member = await this.userRepository.findOne({ id: userId });
if (!member) return false;
if (member.isEmailVerified()) return false;
const isSamePassword = await isSameAsHash(password, user.password);
if (!isSamePassword) {
return fail;
}
return true;
}
}
member.isEmailVerified() 메서드를 호출하여 이메일 검증 상태를 확인합니다. 이것은 member 객체가 자신의 상태를 검사하도록 하는 Tell Don't Ask 원칙을 따른 것입니다. 이것은 캡슐화를 통해 member 객체의 내부 구현을 외부에 감추는 것을 의미합니다.
이메일 검증 상태를 직접 비교하는 대신, member.isEmailVerified() 메서드를 호출하여 검증을 수행합니다. 이렇게 하면 member 객체의 내부 구현이 변경되더라도 해당 메서드만 수정하면 되므로 코드 변경의 범위가 최소화됩니다.
이러한 변경으로 인해 코드는 객체 지향 원칙을 준수하며, 유지보수성이 향상되고 코드가 더 명확해졌습니다. 객체의 내부 구현을 외부로부터 감추는 것은 캡슐화의 핵심 원칙 중 하나이며, 코드를 더 견고하고 유연하게 만드는데 도움이 됩니다.
class Rental {
private daysRented: number;
constructor(private readonly movie: Movie) {}
getFrequentRenterPoints() {
if (this.movie.getPriceCode() === Movie.NEW_RELEASE && this.daysRented > 1)
return 2;
else return 1;
}
}
class Movie {
static REGULAR = 0;
static NEW_RELEASE = 1;
private priceCode: number;
getPriceCode() {
return this.priceCode;
}
}
출처: 리펙토링 (마틴 파울러 저)
class Rental {
private daysRented: number;
constructor(private readonly movie: Movie) {}
getFrequentRenterPoints() {
return this.movie.getFrequentRenterPoints(this.daysRented);
}
}
class Movie {
static REGULAR = 0;
static NEW_RELEASE = 1;
private priceCode: number;
getFrequentRenterPoints(daysRented: number) {
if (this.priceCode === Movie.NEW_RELEASE && daysRented > 1) return 2;
else return 1;
}
}
Rental 클래스에서 getFrequentRenterPoints 메서드가 영화 종류에 따라 다른 포인트를 반환해야 할 때, 이 작업을 Movie 클래스의 getFrequentRenterPoints 메서드로 위임합니다. 이렇게 하면 Rental 클래스가 직접 포인트를 계산하는 것이 아니라 Movie 클래스에게 그 역할을 맡기므로, 객체의 역할과 책임이 분명하게 정의되어 코드의 이해와 유지보수가 용이해졌습니다.