CS/언어

[JAVA] 객체지향 설계 - 객체지향 4대 특성

pythaac 2022. 6. 26. 11:01

https://khalilstemmler.com/articles/object-oriented/programming/4-principles/

 

4 Principles of Object-Oriented Programming | Khalil Stemmler

The four principles of object-oriented programming (abstraction, inheritance, encapsulation, and polymorphism) are features that - if used properly - can help us write more testable, flexible, and maintainable code.

khalilstemmler.com

 

객체지향 4대 특성

  • 추상화 (Abstraction)
  • 상속 (Inheritance)
  • 다형성 (Polymorphism)
  • 캡슐화 (Encapsulation)

https://khalilstemmler.com/articles/object-oriented/programming/4-principles/

 

추상화 (Abstraction)

  • 예시
    - 우리는 TV를 켤 때 리모컨의 on 버튼을 누름
    - on을 눌러 TV가 어떻게 켜지는지 우리는 알 필요가 없음
  • 목적 : Simplify
    • 의도를 드러내고
    • 사용하기 쉽고
    • 이해하고 쉽도록
  • 효과
    • what과 how를 분리
    • 명령형(imperative)과 선언형(declarative)을 분리

 

상속 (Inheritance)

  • 목적 : Reuse
    • [참고] TDD에서는 코드가 3번 반복되면 추상화로 리팩토링 해야한다라는 말이 있음 (Rule of Three)
    • 중복 코드를 줄이고, High-level detail에 집중

https://khalilstemmler.com/articles/object-oriented/programming/4-principles/

  •  특징
    • Abstraction에 의존
    • base class는 low-level 내용을 추상화시키고, subclass는 high-level 내용에 집중할 수 있음
  • 역할
    • 보통 상속은 현실 세계의 "계층"으로 표현
      - Animal-Dog
      - Person-Staff-Teacher
    • 소프트웨어 설계의 목표
      1. 고객의 needs 만족하는 코드 작성
      2. 개발자에 의해 비용 효율적으로 바뀌는 코드 작성
    • 상속은 2번에 도움을 줌
      - 따라서, 상속은 현실세계의 "계층" 표현을 위한 것이 아님
      - "재사용"을 위한 도구로 사용
  • Delegation & Composition
    • "계층"을 무시함으로써 composition & delegation으로 상속 구현
    • Inheritnace (extract superclass) vs Composition (extract another class)
    • [참고] https://pythaac.tistory.com/467
 

[JAVA] Delegation & Composition & Aggregation

https://stackoverflow.com/questions/1384426/distinguishing-between-delegation-composition-and-aggregation-java-oo-design Distinguishing between delegation, composition and aggregation (Java OO Desig..

pythaac.tistory.com

 

캡슐화 (Encapsulation)

  • 배경
    • 객체는 "상태"를 포함하고, 해당 상태를 기반으로 결정을 내림
    • 따라서 객체 자신의 상태를 관리하고, class 외부에서의 조작으로부터 지키는 것이 중요
    • 이에 실패할 경우
      - 이상한 behavior를 초래
      - 버그 발생
      - "빈약한 도메인 모델"

https://khalilstemmler.com/articles/object-oriented/programming/4-principles/

  •  정의
    • private 상태를 만들 수 있는 기술
    • 자신의 상태를 가지는 클래스가 상태에 접근하고 바꿀 수 있는 degree를 결정하는 것
  • 특징
    • data와 관련 behaviour가 결합
    • 한 곳에서 관련 logic을 모을 수 있음
    • (abstraction처럼) 사용하기 쉬움
  • 빈약한 도메인 모델 (anemic domain model)
    • data와 operation(behaviour)이 분리되어 따로 동작하는 모델
    • 구성
      • entity
        - data가 담김
      • stateless service
        - entity를 사용하여 동작
    • 단점
      • discoverability
        - IntelliSense로 객체의 용도를 쉽게 파악할 수 없어, 코드 중복 발생 가능
      • duplication
        - data 주변에 method가 없으면 위치를 찾기 어려워, 코드 중복 발생 가능
      • 🌟lack of encapsulation
        - 위 두 가지는 피할 수 있으나, 이는 피할 수 없음
        - complexity 증가

https://danielrusnok.medium.com/what-is-anemic-domain-model-and-why-it-can-be-harmful-2677b1b0a79a

 

What is Anemic Domain Model and why it can be harmful?

Anemic Domain Model is a common approach in software development that many folks don’t even know they are using it including myself. If…

danielrusnok.medium.com

 

다형성 (Polymorphism)

  • 정의
    • 다양한 형태를 가지는 것
    • 항상 같은 high-level behavior지만, 동적인 low-level behavior를 가짐
    • [참고] 리스코브 치환 원칙 (Liskov-Subsitution Principle)
  • 사용 예시
    • 가게 직원(Clerk)의 responsibility를 정의할 수 있음
      - 상품에 대한 고객의 질문 응대
      - 상품 스캔
      - 가방에 물건 담기
      - 고객에게 비용 지불 요청
    • 그런데 Clerk들이 조금씩 다름
      - 발랄한 직원
      - 골똘한 직원
      - 항상 시간을 지키는 직원
      - 매니저지만 가끔 도와주는 직원
    • 위 직원들은 모두 다르지만, 가게 직원으로써의 의무는 같음

https://khalilstemmler.com/articles/object-oriented/programming/4-principles/

  • role/contract에 의존할 때 장점
    • Dependency inversion을 이용하여 core code와 infrastructure code를 분리
    • Unit test
      - "StripeAPI, PaypalAPI"와 같은 infrastructure dependency를 "MockPaymentAPI"와 같은 테스트용으로 swap
      - 테스트 할 때 외부의 service 또는 infrastructure에 실제 call을 날리지 않도록 하는 목적