Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Refactor | CAKK-59 | Message Extractor, Sender 관련 리팩토링 #199

Merged
merged 12 commits into from
Aug 30, 2024

Conversation

lcomment
Copy link
Collaborator

Issue Number

CAKK-59

Description

리팩토링을 진행하다보니 시간이 꽤 걸리고, 꽤 많은 부분이 변경됐습니다. 다음은 제가 신경 쓴 부분입니다.

  • external 모듈이 내부 비즈니스를 알고 있다.
    • external 모듈은 외부 모듈로, 메일, 슬랙 전송, s3 관련 등 외부 의존성을 지니고 있음
    • (초기에 수립한 모듈 제약 조건에 의거하여) 사업자 인증, 이메일 인증 등의 내부 비즈니스에 대해 알아서는 안됨
    • 현재 뚜렷하게 알고 있는 상태
  • 메일과 슬랙을 활용한 기능들은 모두 external 모듈을 활용함과 동시에 메시지와 관련이 있다.
    • 각 구현 클래스들은 특정 책임을 가지고 있지만, 각각 메시지 추출, 메시지 전송이라는 공통점이 있음

위와 같은 부분을 고려하여 external 모듈에게서 내부 비즈니스를 숨기고, 그 과정에서 Certification이나 Verification이 아닌 Message라는 공통점으로 추상화를 진행하였습니다. 추가적으로, 현재 API 모듈에서 slack 의존성을 받아 slackService를 구현하여 에러 로그를 슬랙에 전송하는 비즈니스가 있는데, 이 부분 또한 리팩토링 하였습니다.

  1. MessageExtractor
fun interface MessageExtractor<T, U> {

	fun extract(message: T): U
}

위와 같이 간단한 함수형 인터페이스로 구성하였고, 각 메시지 플랫폼 별로 인터페이스를 추가 구성했습니다. 아래는 클래스 다이어그램입니다.

  1. MessageSender

MessageSender의 경우, 저번 PR과 동일합니다.

  1. MessageTemplate

기존의 CertificationTemplate이 MessageTemplate으로 변경되었습니다.

class MessageTemplate<T, U> {

	fun sendMessage(
		message: T,
		messageExtractor: MessageExtractor<T, U>,
		messageSender: MessageSender<U>,
	) {
		val extractMessage: U = messageExtractor.extract(message)
		messageSender.send(extractMessage)
	}
}

기존과 다르게 필드에서 의존성을 제거하고 메서드의 파라미터를 통해 전략을 받는 템플릿 콜백 패턴을 구현하였습니다. 다음은 전략 패턴, 템플릿 메서드 패턴, 템플릿 콜백 패턴에 대한 내용입니다.

전략 패턴

: 객체들이 할 수 있는 행위 각각에 대해 전략 클래스를 생성하고, 유사한 행위들을 캡슐화 하는 인터페이스를 정의하여, 객체의 행위를 동적으로 바꾸고 싶은 경우 직접 행위를 수정하지 않고 전략을 바꿔주기만 함으로써 행위를 유연하게 확장하는 방법

템플릿 메서드 패턴

: 코드에 변하는 부분과 변하지 않는 부분이 있을 때, 변하지 않는 부분추상 클래스 내 메서드로 정의하고, 변하는 부분추상 클래스 내 abstract 메서드로 정의하여 자식 클래스에서 변하는 부분을 abstract 메서드를 override 하여 구현하는 패턴

템플릿 콜백 패턴

: 전략 패턴과 템플릿 메서드 패턴이 합쳐진 형태로, 전략 패턴과 다르게, Strategy를 필드에 가지고 있지 않고, 메서드 파라미터로 넘겨받는 방식

  1. 활용

MessageTemplate은 다음과 같이 활용할 수 있습니다.

@ApplicationEventListener
public class EmailSendEventListener {

	private final MessageTemplate messageTemplate;
	private final MessageExtractor messageExtractor;
	private final MessageSender messageSender;

	// Bean이 여러 개 있으므로 Qualifier로 어떤 Bean인지 선택하여 주입
	public EmailSendEventListener(
		MessageTemplate messageTemplate,
		@Qualifier("verificationCodeMimeMessageExtractor") MessageExtractor messageExtractor,
		@Qualifier("emailMessageSender") MessageSender messageSender
	) {
		this.messageTemplate = messageTemplate;
		this.messageExtractor = messageExtractor;
		this.messageSender = messageSender;
	}

	@Async
	@EventListener
	public void sendEmailIncludeVerificationCode(EmailWithVerificationCodeSendEvent event) {
		final VerificationMessage verificationMessage = EventMapper.supplyVerificationMessageBy(event);
		messageTemplate.sendMessage(verificationMessage, messageExtractor, messageSender);
	}
}

사업자 인증 또한 위와 같이 리팩토링 하였고, SlackService를 활용하고 있던 에러 관련 슬랙 로깅 또한 리팩토링 후 API 모듈에서 Slack 관련 의존성을 제거 하였습니다.

etc

@lcomment lcomment added the refactor 비즈니스 변경 없는 수정 label Aug 30, 2024
@lcomment lcomment requested a review from YongsHub August 30, 2024 08:05
@lcomment lcomment self-assigned this Aug 30, 2024
Copy link

github-actions bot commented Aug 30, 2024

Test Results

 40 files   40 suites   24s ⏱️
215 tests 215 ✅ 0 💤 0 ❌
216 runs  216 ✅ 0 💤 0 ❌

Results for commit 6f9899a.

♻️ This comment has been updated with latest results.

Copy link

codecov bot commented Aug 30, 2024

Codecov Report

All modified and coverable lines are covered by tests ✅

Impacted file tree graph

@@              Coverage Diff              @@
##             develop     #199      +/-   ##
=============================================
+ Coverage      89.11%   92.84%   +3.73%     
- Complexity       326      330       +4     
=============================================
  Files            110      109       -1     
  Lines            983      965      -18     
  Branches          37       34       -3     
=============================================
+ Hits             876      896      +20     
+ Misses            88       52      -36     
+ Partials          19       17       -2     
Files with missing lines Coverage Δ Complexity Δ
...ava/com/cakk/api/config/MessageTemplateConfig.java 100.00% <100.00%> (ø) 4.00 <4.00> (?)
.../api/controller/advice/GlobalControllerAdvice.java 100.00% <100.00%> (ø) 11.00 <2.00> (+1.00)
...n/java/com/cakk/api/dto/event/ErrorAlertEvent.java 100.00% <100.00%> (ø) 1.00 <1.00> (?)
.../cakk/api/listener/CertificationEventListener.java 100.00% <100.00%> (ø) 2.00 <1.00> (+1.00)
.../com/cakk/api/listener/EmailSendEventListener.java 100.00% <100.00%> (ø) 2.00 <0.00> (+1.00)
...com/cakk/api/listener/ErrorAlertEventListener.java 100.00% <100.00%> (ø) 2.00 <2.00> (?)
...src/main/java/com/cakk/api/mapper/EventMapper.java 96.29% <100.00%> (+2.96%) 6.00 <2.00> (+3.00)

... and 6 files with indirect coverage changes


Continue to review full report in Codecov by Sentry.

Legend - Click here to learn more
Δ = absolute <relative> (impact), ø = not affected, ? = missing data
Powered by Codecov. Last update e90c9dc...6f9899a. Read the comment docs.

Copy link
Contributor

@YongsHub YongsHub left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

좋은 추상화로 작동되는 것 같습니다 고생하셨습니다!

@lcomment lcomment merged commit 0346e96 into develop Aug 30, 2024
3 checks passed
@lcomment lcomment deleted the refactor/CAKK-59 branch August 30, 2024 11:46
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
refactor 비즈니스 변경 없는 수정
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants