✏️9.2 필드 이름 바꾸기 (Rename Field)

리팩터링 전

class Organization {  
    get name() {...}
}

리팩터링 후

class Organization {  
    get title() {...}
}

🧷 배경

프로그램 곳곳에서 쓰이는 레코드 구조체의 필드 이름은 중요하다. 데이터 구조는 프로그램을 이해하는 데 큰 역할을 한다.

🧷 절차

  1. 레코드의 유효 범위가 제한적이라면 필드에 접근하는 모든 코드를 수정한 후 테스트한다. 이후 단계는 필요 없다.

  2. 레코드가 캡슐화되지 않았다면 우선 레코드를 캡슐화(7.1절)한다.

  3. 캡슐화된 객체 안의 private 필드명을 변경하고, 그에 맞게 내부 메서드들을 수정한다.

  4. 테스트한다.

  5. 생성자의 매개변수 중 필드와 이름이 겹치는 게 있다면 함수 선언 바꾸기(6.5절)로 변경한다.

  6. 접근자들의 이름도 바꿔준다(6.5절).

🧷 예시

// 상수
const organization = {name: '애크미 구스베리', country: 'GB'};

name을 title로 바꿔보자.

  1. organization 레코드를 클래스로 캡슐화한다.

class Organization {
    constructor(data) {
        this._name = data.name;
        this._country = data.country;
    }
    get name()    {return this._name;}
    set name(aString) {this._name = aString;}
    get country()    {return this._country;}
    set country(aCountryCode)    {this.country = aCountryCode;}
}
const organization = new Organization({name: '애크미 구스베리', country: 'GB'};)

레코드를 캡슐화하면 이름을 변경할 곳이 게터 함수, 세터 함수, 생성자, 내부 데이터 구조 네곳이다.

  1. 별도의 필드를 정의하고 생성자와 접근자에서 둘을 구분해 사용하자.

  2. 생성자에서 title도 받아들일 수 있도록 한다.

class Organization {
    constructor(data) {
        this._title = (data.title !== undefined) ? data.title : data.name;
        this._country = data.country;
    }
    get name()    {return this._title;}
    set name(aString) {this._title = aString;}
    get country()    {return this._country;}
    set country(aCountryCode)    {this.country = aCountryCode;}
}
  1. name을 사용할 수 있게 하던 코드를 제거한다.

  2. 접근자를 수정한다.

class Organization {
    constructor(data) {
        this._title = data.title;
        this._country = data.country;
    }
    get title()    {return this._title;}
    set title(aString) {this._title = aString;}
    get country()    {return this._country;}
    set country(aCountryCode)    {this.country = aCountryCode;}
}

가변 데이터 구조를 이용한다면 데이터를 복제하는 것은 재앙이다. 불변 데이터 구조가 널리 쓰이게 된 이유는 재앙을 막기 위해서이다.

Last updated