루비로 배우는 객체지향 디자인 - 4장 유연한 인터페이스 만들기

By: Jun Heo
Posted: October 08, 2021

"메세지를 전송해야 하는데 누구에게 전송해야 하지?"라고 질문하는 것이 좋은 디자인을 위한 시작이다.

데메테르 원칙(Law of demeter)이란?

다른 객체가 어떤 자료를 가지고 있는지 몰라야 한다. 결합도를 낮추기 위해서 객체에게 자료를 숨기는 대신 함수를 공개한다.

데메테르 예시

서울에 살고 있는 사용자에게 알림을 하는 메소드

@Getter public class User {
    private String email;
    private String name;
    private Address address;
}
@Getter public class Address {
    private String region;
    private String details;
}
@Service public class NotificationService {
    public void sendMessageForSeoulUser(final User user) {
        if ("서울".equals(user.getAddress().getRegion())) {
            sendNotification(user);
        }
    }
}

@Getter public class User {
    private String email;
    private String name;
    private Address address;
    
    public boolean isRegionUser(region) {
    	return address.isRegion(region);
    }
}
@Getter public class Address {
    private String region;
    private String details;
    
    public boolean isRegion(region) {
    	return this.region.equals(region);
    }
}
@Service public class NotificationService {
    public void sendMessageForSeoulUser(final User user) {
        if (user.isRegionUser("Seoul")) {
            sendNotification(user);
        }
    }
}

데메테르 원칙 참고링크

https://mangkyu.tistory.com/147