Strength & Honor


리팩토링


리팩토링이란 코드 작성 후 비효율적인 면이 있는 부분을 효율적인 코드로 개선시켜 가독성을 높이고 유지보수를 하기 편하게 하고 중복된 코드를 줄이는 등, 코드를 개선하는 작업을 말한다.
이렇게 하는 이유는 코드의 양이 많으면 많을수록 시스템이 커지고 연산시 시간이 많이 소요되기 때문이다.

가장 기본적인 것이 바로 코드에 여러번 동일하게 사용되는 값이나 명령을 변수화 시키는 것이다.
즉 예를들어 아래 코드에서 document.querySelector('body') 을 target 이라는 변수로 바꾸면


코드는 아래와 같다.

    
    <input type='button' value='night' onclick="
        var target = document.querySelector('body');
        if(target.dataset.mode === 'day'){
            target.style.backgroundColor='black';
            target.style.color='white';
            target.dataset.mode = 'night';
            this.value = 'day';
        }
        else {
            target.style.backgroundColor='white';
            target.style.color='black';
            target.dataset.mode = 'day';
            this.value = 'night';
        }
    ">