코드 냄새 78 - 콜백 지옥

일련의 중첩된 콜백으로 알고리즘을 처리하는 것은 영리하지 않습니다.

TL;DR: Don't process calls in a callback way. Write a sequence.



문제


  • 가독성
  • 디버그하기 어렵습니다.
  • 복잡성

  • 솔루션


  • 콜백을 시퀀스 호출로 변경합니다.
  • 반복 코드 추출
  • 리팩토링.

  • 샘플 코드



    잘못된




    var fs = require('fs');
    
    var fileWithData = '/hello.world';  
    fs.readFile(fileWithData, 'utf8', function(err, txt) {  
        if (err) return console.log(err);
    
        txt = txt + '\n' + 'Add Data!';
        fs.writeFile(fileWithData, txt, function(err) {
            if(err) return console.log(err);
            console.log('Information added');
        });
    });
    

    오른쪽



    var fs = require('fs');
    
    function logTextWasAdded(err) {  
        if(err) return console.log(err);
        console.log('Information added');
    };
    
    function addData(error, actualText) {  
        if (error) return console.log(error);
    
        actualText = actualText + '\n' + 'Add data';
        fs.writeFile(fileWithData, actualText, logTextWasAdded);
    }
    
    var fileWithData = 'hello.world';  
    fs.readFile(fileWithData, 'utf8', addData);  
    

    발각



    이 문제는 육안으로 볼 수 있습니다. 많은 린터가 이러한 복잡성을 감지하고 경고할 수 있습니다.

    태그


  • 가독성
  • 복잡성

  • 결론



    콜백 지옥은 미래나 약속이 있는 프로그래밍 언어에서 매우 흔한 문제입니다.

    콜백은 점진적으로 추가됩니다. 초반에는 별 무리가 없습니다.

    리팩토링이 없는 복잡성은 읽고 디버깅하기 어렵게 만듭니다.

    처지








    There are two ways to write code: write code so simple there are obviously no bugs in it, or write code so complex that there are no obvious bugs in it.



    토니 호어






    이 기사는 CodeSmell 시리즈의 일부입니다.


    좋은 웹페이지 즐겨찾기