-
[Refactoring] 21. 서로 다른 인터페이스의 대안 클래스들클린코드 2022. 9. 25. 17:52
코딩으로 학습하는 리팩토링 - 인프런 | 강의
리팩토링은 소프트웨어 엔지니어가 갖춰야 할 기본적인 소양 중 하나입니다. 이 강의는 인텔리J와 자바를 사용하여 보다 실용적인 방법으로 다양한 코드의 냄새와 리팩토링 기술을 설명하고 직
www.inflearn.com
| 인프런 - 백기선님의 코딩으로 학습하는 리팩토링 강의를 수강하며 정리한 글입니다.
서로 다른 인터페이스의 대안 클래스들
- 비슷한 일을 여러 곳에서 서로 다른 규약을 사용해 지원하고 있는 경우
- 대안 클래스로 사용하려면 동일한 인터페이스를 구현하고 있어야 한다.
- 관련 리팩토링
- 한수 선언 변경하기, 함수 옮기기 -> 서로 동일한 인터페이스를 구현하게끔 코드를 수정할 수 있다.
- 슈퍼 클래스 추출하기 -> 중복된 코드를 슈퍼 클래스로 옮기고 두 클래스를 새로운 슈퍼 클래스의 서브 클래스로 만들 수 있다.
Before
public class OrderAlerts { private AlertService alertService; public void alertShipped(Order order) { AlertMessage alertMessage = new AlertMessage(); alertMessage.setMessage(order.toString() + " is shipped"); alertMessage.setFor(order.getEmail()); alertService.add(alertMessage); } } public class OrderProcessor { private EmailService emailService; public void notifyShipping(Shipping shipping) { EmailMessage emailMessage = new EmailMessage(); emailMessage.setTitle(shipping.getOrder() + " is shipped"); emailMessage.setTo(shipping.getEmail()); emailMessage.setFrom("no-reply@whiteship.com"); emailService.sendEmail(emailMessage); } }
After
public interface NotificationService { void sendNotification(Notification notification); } public class OrderAlerts { private NotificationService notificationService; public OrderAlerts(NotificationService notificationService) { this.notificationService = notificationService; } public void alertShipped(Order order) { Notification notification = Notification.newNotification(order.toString() + " is shipped") .receiver(order.getEmail()); notificationService.sendNotification(notification); } } public class OrderProcessor { private NotificationService notificationService; public OrderProcessor(NotificationService notificationService) { this.notificationService = notificationService; } public void notifyShipping(Shipping shipping) { Notification notification = Notification.newNotification(shipping.getOrder() + " is shipped") .receiver(shipping.getEmail()) notificationService.sendNotification(notification); } } public class EmailNotificationService implements NotificationService { private EmailService emailService; @Override public void sendNotification(Notification notification) { EmailMessage emailMessage = new EmailMessage(); emailMessage.setTitle(notification.getTitle()); emailMessage.setTo(notification.getReceiver()); emailMessage.setFrom("no-reply@whiteship.com"); emailService.sendEmail(emailMessage); } }
=> 배송 정보, 주문 정보 알림을 하나의 Service를 사용해 알림하도록 구현
'클린코드' 카테고리의 다른 글
[Refactoring] 23. 상속 포기하기 (0) 2022.09.27 [Refactoring] 22. 데이터 클래스 (1) 2022.09.26 [Refactoring] 20. 거대한 클래스 (0) 2022.09.24 [Refactoring] 19. 내부자 거래 (1) 2022.09.23 [Refactoring] 18. 중재자 (0) 2022.09.22