상세 컨텐츠

본문 제목

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

🍜개발자라면/책을 읽자✍

by :Eundms 2021. 9. 25. 14:24

본문

- 레코드 구조체의 필드 이름

- 클래스 내 필드

- 클래스 내 사용하는 부분, getter, setter메서드 

 

 


방법

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

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

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

4. 테스트한다.

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

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

 

 


  필드 이름 바꾸기  

const organization = {name : "삼성", country: "KOR"};
name을 title로 바꾸고 싶다.
organization은 널리 참조되는 데이터 구조이다.

 

// 변경 이전
const organization = {name: "삼성", country : "KOR"}

// 1) 캡슐화
class Organization {
    constructor(data){
        this._name = data.name;   // _name과 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:"KOR"});


// 2) 별도의 필드를 정의하고 생성자와 접근자에서 둘을 구분해(name,_title) 사용하도록 한다.
class Organization {
    constructor(data){
        this._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; }
}

// 3) data.title로도 받아들일 수 있도록 한다
// {title:"삼성",country:"KOR"}, {name:"삼성",country:"KOR"} 둘 다 가능하게
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; }
}

// 4) 생성자에서 data.title로만 받아들일 수 있게 바꾼다.
class Organization {
    constructor(data){
        this._title = data.title; //*
        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; }
}

//5) getter,setter이름도 변경해준다.
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; }
}

> 만약, 데이터 구조를 불변으로 만들 수 있는 프로그래밍 언어를 사용한다면

캡슐화하는 대신 데이터 구조의 값을 복제해 새로운 이름으로 선언한다.

그런 다음 사용하는 곳을 찾아 하나씩 새 데이터를 사용하도록 수정하고, 마지막으로 원래의 데이터 구조를 제거하면 된다. 가변 데이터 구조를 이용한다면 데이터를 복제하는 행위가 재앙으로 이어질 수 있다. 

 

 

 

 

관련글 더보기

댓글 영역