Encapsultion(2) - Encapsulate Collection

Kerem Song·2021년 4월 5일
0

Refactoring - Study

목록 보기
15/22

A method returns a collection. Make it return a read-only view and provide add/remove methods
(컬렉션 변수로의 접근을 캡슐화 하면서 게터가 컬렉션 자체를 반환하도록 한다면, 그 컬렉션을 감싼 클래스가 눈치채지 못하는 상태에서 컬렉션의 원소들이 바뀌어 버릴수 있다. 이런 것을 방지하기 위해 컬렉션 변경자 메소드를 만든다. 컬렉션을 소유한 클래스를 통해서만 원소를 변경하도록 하면, 프로그램을 개선하면서 컬렉션 변경 방식도 원하는 대로 수정할 수 있다.)

class Person {
  get courses() { return this._courses }
  set courses(aList) { this._courses = aList }
}

to

class Person {
  get courses() { return this._courses.slice() }
  addCourse(aCourse) {}
  removeCourse(aCourse)
}

Motivation

  1. Change to the collection should go through the owning class to prevent unexpected changes.
    컬렉션을 소유한 클래스를 통해서만 원소를 변경하도록 하면, 예기치 않은 변경을 방지할 수 있다.

  2. Prevent modification of the underlying collection for example: return a copy or read-only proxy instead of collection value
    기본 컬렉션 수정 방지(예: 컬렉션 값 대신 복사본 또는 읽기 전용 프록시 반환)

Procedure

  1. If you have not already encapsulated the collection, you start by encapsulating the variables.
    아직 컬렉션을 캡슐화하지 않았다면 변수 캡슐화하기부터 한다.

  2. Adds a function that adds/removes elements to the collection.
    컬렉션에 원소를 추가/제거하는 함수를 추가한다.

  3. Do static inspection.
    정적 검사를 수행한다.

  4. Find all the parts that reference the collection. Modify the code calling the modifiers in the collection to call the add/remove function that you added earlier. Test each modification.
    컬렉션을 참조하는 부분을 모두 찾는다. 컬렉션의 변경자를 호출하는 코드가 모두 앞에서 추가한 추가/제거 함수를 호출하도록 수정한다. 하나씩 수정할 때마다 테스트한다.

  5. Modify the collection getter to return a read-only proxy or replica that cannot modify the original content.
    컬렉션 게터를 수정해서 원본 내용을 수정할 수 없는 읽기전용 프록시나 복제본을 반환하게 한다.

  6. Test it.
    테스트 한다.

profile
Tea and Dessert

0개의 댓글