[4주차] Refactoring ( 중복 code 합치기 )

김_리트리버·2020년 8월 17일
0
post-thumbnail

[Refactoring]

  • 팀원이 작성한 코드중에 중복되는 부분을 발견했다.
  • 옷 data 입력 시 12가지 type 을 선택할 수 있었다.
  • 팀원은 type 을 선택할 때 호출되는 함수를 12개를 선언해 코드를 작성했다.
  • 코드양이 많아지니 추가, 수정하기 힘들었다.
  • 하나의 함수로 변경하고 type 을 선택할 때 type 에 맞는 전달인자로 함수를 호출하는 것으로 변경했다.

< Before Refactoring >


//before => selectXXX() 함수가 12개.. 
function selectTop() {

        setSelectType({ ...selectTypeObject, top: true });

        const clothingTypeObj = {
            typeValue: 'top',
            top: true,
            bottom: false,
            outer: false,
            dress: false
        };
        ClothesActions
            .setTemporaryClothing(temporaryClothing.set('type', Map(clothingTypeObj)));
    };

    function selectBottom() {

        setSelectType({ ...selectTypeObject, bottom: true });

        const clothingTypeObj = {
            typeValue: 'bottom',
            top: false,
            bottom: true,
            outer: false,
            dress: false
        };
        ClothesActions
            .setTemporaryClothing(temporaryClothing.set('type', Map(clothingTypeObj)));
    };

변경전 return 부분


            <Chip
                        onPress={selectTop}
                        style={styles.chip}
                        selected={selectType.top}
                        textStyle={{ fontSize: 15 }}>
                        👕 상의
                    </Chip>
                    <Chip
                        onPress={selectBottom}
                        style={styles.chip}
                        selected={selectType.bottom}
                        textStyle={{ fontSize: 15 }}>
                        👖 하의
                    </Chip>

< After Refactoring >

function selectType(type) {
        let typeObject = { ...defaultTypeObject, typeValue: `${type}` }
        typeObject[`${type}`] = true;
              ClothesActions.setTemporaryClothing(temporaryClothing.set('type', Map(typeObject)));
    }

변경 후 return 부분

특정 type 을 선택할 때 개별 함수를 호출하지 않고
같은 함수를 argument 를 다르게 하여 호출하는 형태로 변경하였다.
기존 12개 함수를 선언한 것을 1개로 줄일 수 있었다.


 <Chip
                     
                        onPress={() => { selectType('top') }}
                        style={styles.chip}
                       
                        selected={temporaryClothing.get('type').get('top')}
                        textStyle={{ fontSize: 15 }}>
                        👕 상의
                    </Chip>
                    <Chip
                       
                        onPress={() => { selectType('bottom') }}
                        style={styles.chip}
                    
                        selected={temporaryClothing.get('type').get('bottom')}
                        textStyle={{ fontSize: 15 }}>
                        👖 하의
                    </Chip>
profile
web-developer

0개의 댓글