Encapsultion(1) - Encapsulate Record

Kerem Song·2021년 4월 5일
0

Refactoring - Study

목록 보기
14/22

Encapsulate Record

Create record (class) from object
(객체로부터 레코드(클래스)를 만든다)

organization = {name: "Acme gooseberries", country: "GB"}

to

class Organization {
  constructor(data) {
    this._name = data.name
    this._country = data.country
  }

  get name() { return this._name }
  set name(arg) { this._name = arg }
  get country() { retrun this._country }
  set country(arg) { this._country = arg }
}

Motivation

  1. Hide what's stored and provide methods to get value
    객체를 사용하면 어떻게 저장했는지를 숨긴 채 세가지 값을 각각 메소드로 제공할 수 있다.
    사용자는 무엇이 저장된 값이고 무엇이 계산된 값인지 알 필요가 없다.
    이름을 바꿀 때도 좋다.
    필드 이름을 바꿔도 기존 이름과 새 이름 모두를 각각의 메소드로 제공할 수 있어서 사용자 모두가 새로운 메소드로 옮겨갈 때까지 점진적으로 수행할 수 있다.

  2. Easier to refactoring, for example: rename
    리팩토링 하기에 용이하다.

Procedure

  1. Encapsulates the variable containing the record.
    레코드를 담은 변수를 캡슐화한다.

  2. Replace the contents of the corresponding variable with a simple class surrounding the record. Also define an accessor that returns the original record to this class, and modify the functions that encapsulate the variable to use this accessor.
    레코드를 감싼 단순한 클래스로 해당 변수의 내용을 교체한다. 이 클래스에 원본 레코드를 반환하는 접근자도 정의하고, 변수를 캡슐화하는 함수들이 이 접근자를 사용하도록 수정한다.

  3. Test it.
    테스트한다.

  4. Create new functions that return newly defined class-type objects instead of original records.
    원본 레코드 대신 새로 정의한 클래스 타입의 객체를 반환하는 함수들을 새로 만든다.

  5. Changes the code that uses the old function that returns the record to use the new function created in step 4. Use the object's accessor to access the field. If there is no appropriate access, add it. Test every time a part is changed.
    레코드를 반환하는 예전 함수를 사용하는 코드를 4단계에서 만든 새함수를 사용하도록 바꾼다. 필드에 접근할 때는 객체의 접근자를 사용한다. 적절한 접근자가 없다면 추가한다. 한 부분을 바꿀 때마다 테스트한다.

  6. Removes an accessor that returns the original data from the class and functions that return the original record (named easy to search in step 1).
    클래스에서 원본 데이터를 반환하는 접근자와 (1단계에서 검색하기 쉬운 이름을 붙여둔) 원본 레코드를 반환하는 함수들을 제거한다.

  7. Test it.
    테스트한다.

  8. If the fields of a record are also data structures, nested structures, we recursively apply both record encapsulation and collection encapsulation.
    레코드의 필드도 데이터 구조인 중첩 구조라면 레코드 캡슐화하기와 컬렉션 캡슐화하기를 재귀적으로 적용한다.

profile
Tea and Dessert

0개의 댓글