ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 임시 변수 제거
    JavaScript/CleanCode 2022. 10. 6. 13:04

    임시 변수의 문제점?

    - 명령형으로 가득한 로직

    - 어디서 어떻게 잘못되었는지 디버깅이 힘들다

    - 함수를 하나의 역할만 하게 해야하는데, 임시 변수라는 키워드가 추가적인 코드를 작성하고 싶게 유혹하게 된다.

    - 코드 유지보수가 어렵다

     

    임시 변수의 해결책?

    - 함수 나누기

    - 바로 반환(return)

    - 고차함수 사용(map, filter, reduce) 사용

    - 선언형 코드로 바꾸기

     

     

     

    아래 코드를 보면 임시 변수(임시 객체)는 코드가 깔끔하지 않다.

    function getElements() {
        const result = {}; // 임시 객체
    
        result.title = document.querySelector('.title');
        result.text = document.querySelector('.text');
        result.value = document.querySelector('.value');
    
        return result;
    }

     

    아래 코드처럼  명확하게 바꾸거나

    function getElements() {
        const result = {
          title: document.querySelector('.title'),
          text: document.querySelector('.text'),
          value: document.querySelector('.value'),
        };
    
        return result;
    }

     

    객체를 아예 리턴시키자

    function getElements() {
        return {
          title: document.querySelector('.title'),
          text: document.querySelector('.text'),
          value: document.querySelector('.value'),
        };
    }

    'JavaScript > CleanCode' 카테고리의 다른 글

    형변환 주의하기  (0) 2023.02.23
    undefined, null  (0) 2023.02.22
    호이스팅 주의하기  (0) 2023.02.22

    댓글

Designed by Tistory.