정적 팩토리 메소드(static factory method) 는 객체를 생성하기 위한 메소드를 정적으로 정의한 것이다. 일반적으로 직접 객체를 생성하는 대신, 클래스 내에 정적 메소드를 사용하여 객체를 생성하는 패턴을 말한다. 이 방법은 생성자보다 유연하고 명확한 객체 생성 방식을 제공하는 경우가 많다.
// 일반적인 방법
ProfileResponseDto profile = new ProfileResponseDto(profileEntity);
// 정적 팩토리 메소드 사용
ProfileResponseDto profile = ProfileResponseDto.from(profileEntity);
from() 메소드는 객체가 Profile 엔티티에서 만들어진다는 것을 직관적으로 알려준다.from() , of() , valueOf() , getInstance() 등의 이름으로 사용된다.@Getter
public class ProfileResponseDto {
private Long id;
private String bio;
private String profileImage;
private Long follower;
private Long following;
// private 생성자
private ProfileResponseDto(Long id, String bio, String profileImage, Long follower, Long following) {
this.id = id;
this.bio = bio;
this.profileImage = profileImage;
this.follower = follower;
this.following = following;
}
// 정적 팩토리 메소드
public static ProfileResponseDto from(Profile profile) {
return new ProfileResponseDto(
profile.getId(),
profile.getBio(),
profile.getProfileImage(),
profile.getFollower(),
profile.getFollowing()
);
}
} 이렇게 ResponseDto 에서 생성한 정적 팩토리 메소드를 사용하는 방법은 간단하다. from() 이라는 메소드를 호출하여 Profile 객체로부터 ProfileResponseDto 를 생성한다.Profile profile = profileRepository.findById(profileId)
.orElseThrow(() -> new IllegalArgumentException("Profile not found"));
ProfileResponseDto profileResponseDto = ProfileResponseDto.from(profile); from() 이라는 메소드명은 객체가 특정 데이터로부터 생성된다는 것을 명확하게 알려준다.public static ProfileResponseDto empty() {
return new ProfileResponseDto(null, "자기소개를 입력해주세요", "/images/basic-profile.png");
}private 로 만들고 정적 팩토리 메소드만 노출시킴으로써 객체의 생성 과정을 캡슐화할 수 있다. 이렇게 하면 생성자 호출을 제한하고 원하는 로직에 따라 객체를 생성할 수 있게 된다.from() 메소드를 통해 객체를 생성하므로 변경에 의한 영향을 최소화할 수 있다. 필드 추가 시에도 내부 생성자만 수정하면 된다.과제를 하면서 항상 캡슐화에 대한 요구를 많이 받았다. 개념은 머리속에 박혀있지만, 막상 개발을 할때는 캡슐화는 사라지고 익숙한 getter setter 를 남발을 하였다. 이번에도 역시나 기능 구현에만 급급하였고, 중간에 피드백을 받은 내용이 캡슐화에 대한 내용이었고, 그중에 한가지 방법이 정적 팩토리 메소드의 사용이었다. 아직 익숙하지 않은 코드라 좀 더 숙지를 하고 사용하는 방법도 있겠지만, 좋은 방법을 바로 적용하면서 사용하는 것도 내것으로 만드는 좋은 방식이라 생각한다. 앞으로 개발은 이런 방식으로 도전을 해봐야겠다.