SlideShare una empresa de Scribd logo
1 de 43
리팩토링 개요

     SEEG
SW 프로젝트에서 개발자를 괴롭히는 악당들이 있습니다
악당1. 시도 때도 없는 요구사항 변경
악당2. 말도 안 되는 몰상식한 일정(추정)

월   화   수   목   금   금   금   월   화   수   목   금   금   금
월   화   수   목   금   금   금   월   화   수   목   금   금   금
월   화   수   목   금   금   금   월   화   수   목   금   금   금
월   화   수   목   금   금   금   월   화   수   목   금   금   금
월   화   수   목   금   금   금   월   화   수   목   금   금   금
월   화   수   목   금   금   금   월   화   수   목   금   금   금
월   화   수   목   금   금   금   월   화   수   목   금   금   금
월   화   수   목   금   금   금   월   화   수   목   금   금   금
월   화   수   목   금   금   금   월   화   수   목   금   금   금
SW 프로젝트는 폭주하게 됩니다
SW 프로젝트 폭주의 결과로… 퇴사를 합니다
이렇게 되면 우리 코드에 무슨 일이 생길까요?
이렇게 됩니다   “얼마 못 사시겠습니다”
왜, 이렇게 되었을까요?
이러한 문제를 해결해보고자 하는 공학적 접근법




         Reengineering
              요즘은



          Refactoring
            이라고도 합니다
물론 Refactoring이 근본 해결책은 아닙니다
Refactoring은 여러 대안 중 하나입니다
Reengineering vs Refactoring




      잠시 동안 살 수 없어요            살면서 할 수 있어요
Reengineering vs Refactoring정의

 Reengineering
 } Chikofsky and Cross, "The examination and alteration of a system
   to reconstitute it in a new form".
 } the modification of a software system that takes place after it has
   been reverse engineered, generally to add new functionality, or to
   correct errors.

 Refactoring
 } Martin Fowler, "disciplined technique for restructuring an existing
   body of code, altering its internal structure without changing its
   external behavior",
 }   undertaken in order to improve some of the nonfunctional
     attributes of the software
 }   Tiny change in a computer program's source code that does NOT
     modify its functional requirements.
Keyword 차이



                   Reegineering                  Refactoring



        Reverse Engineering
                                                      Internal structure
       (legacy code analysis)
                                    Readability
      Restructuring             decrease complexity
                                                          Tiny change
 (Fine-grained structure)         Maintainability
                                     extensibility

          New functionality
                                                      Non functionality
프로세스 차이

Reengineering

 Legacy code        To be
                                Restructuring   Refactoring    System Test
   analysis      architecture




 Refactoring

    Identify      Find test        Break                      Make changes
                                                Write tests
 change points     points       dependencies                   and refactor
구조를 왜 바꾸려는 걸까요?

“코드가 자꾸 늙기 때문이죠”




                       스파게티 코드 다수 존재



                   Feature enhance, bug fixing으로
                         인한 코드 수정 어려움



                   미흡한 영향평가로 new bug 등장



                         코드 수정 비용 증가
언제, 어떻게 Refactoring을 해야 하는가?

 }   틈틈이 계속
     }   리팩토링 자체가 목적이 아니라, 다른 것을 하기 위해 리팩토링을 하는 것이고, 리팩토링은 그
         다른 것을 하는데 도움을 준다.

 }   삼진 규칙
     }   세 번째로 비슷한 것을 하게 되면 리팩토링을 한다

 }   기능을 추가할 때, 버그를 수정할 때
     }   코드에 대한 이해를 돕기 위해서

 }   코드 검토 시
     }   고수준의 의견을 얻을 수 있음
     }   준비가 많이 필요함

 }   언제 리팩토링을 하지 말아야 하는가?
     }   코드를 처음부터 작성 하는 게 나을 정도로 엉망인 경우
     }   현재의 코드가 작동하지 않을 경우
     }   마감일에 가까울 경우
특히…

구린내(Bad Smell)가 나면 Refactoring을 합니다
구린내(Bad Smell)

 }   구린내(Bad Smell)는 코드에 잠재된 문제에 대한 경
     고 표시

 }   대표적 냄새
     }   Duplicated code
     }   Long method
     }   Long parameter list
     }   Large class
Duplicated Code


 }   가장 많이 발생하는 냄새

 }   해결책
     }   하나의 클래스에서 중복
         } ExtractMethod
     }   두 형제 클래스에서 중복
         } ExtractMethod -> Pull Up Field or Pull Up Method -
           > Form Template Method
Extract Method

 void printOwing()
 {
 printBanner();
 //print details
 System.out.println ("name: " + _name);
 System.out.println ("amount " +
   getOutstanding());
 }
Extract Method (Contd.)

 void printOwing()
 {
 printBanner();
 printDetails(getOutstanding());
 }
 void printDetails (double outstanding)
 {
 System.out.println ("name: " + _name);
 System.out.println ("amount " + outstanding);
 }
Duplicated Code


 Smell
 } same expression in two sibling subclasses


 Refactor
 } Extract method in both classes.
 } Pull up field.
Pull Up Field


 }   Two subclasses have the same field.
 }   Move the field to the superclass.
Pull Up Field (Contd.)
Duplicated Code


 Smell
 } Code is similar but not the same


 Refactor:
 } Use Extract Method to separate the
   similar bits from the different bits.
 } Use Form Template Method.
Form template method


 } 각각의 서브클래스에, 동일한 순서로 비슷한 단
   계를 행하지만, 단계가 완전히 같지는 않은 두
   메소드가 있다면, 그 단계를 동일한 시그너처를
   가진 메소드로 만들어라
 } 이렇게 하면 원래의 두 메소드는 서로 같아지므
   로, 수퍼클래스로 올릴 수 있다.
Form Template Method (Contd.)
Long method

 }   Object program having short methods live best and longest.
 }   Little methods are the most valuable.
 }   Longer methods are difficult to understand.
Extract Method

 }   Cyclomatic Complexity
 }   Essential Complexity
 }   Control Flow
Long Parameter List


  }   Smell
  }   A method call requires passing long list of
      parameters.

  }   Refactor
  }   Use Introduce Parameter Object.
Introduce Parameter Object


      자연스럽게 몰려다니는 파라미터 그룹을 가지고 있다면
      → 그것들을 객체로 바꾸어라




  }   같이 넘겨지는 경향이 있는 특별한 그룹의 파라미터에 대해
      }   -> 데이터 덩어리
      }   -> 객체형태로 묶일 수 있음


  }   부가 효용
      }   새로 생긴 객체에 들어가야 할 메소드가 쉽게 눈에 띔
      }   이에 따라, 중복을 효과적으로 제거할 수 있음
Large Class


  }   Too many responsibilities
  }   Broken SRP
  }   SRP: Every class should have a single responsibility, and that
      responsibility should be entirely encapsulated by the class. All its
      services should be narrowly aligned with that responsibility.
SRP Test
                단일책임원칙(Single Responsibility Principle)
     SRP
                •클래스가 한가지 책임만 가져야 한다는 원칙

                •클래스나 모듈을 변경할 이유가 하나 뿐이어야 함

                •큰 클래스 è 작은 클래스 여럿
                작은 클래스와 협력해 시스템에 필요한 동작 수행



           ____________가 스스로 ___________ 한다.

           각 줄의 첫 번째 공백에 모듈명을 적습니다. 두 번째 공백에 모듈의
           메소드/함수 중 하나를 적습니다. 모듈의 모든 함수/메소드마다 이
           를 수행합니다.

           각 줄을 소리 내어 읽습니다. 읽은 내용을 이해할 수 있습니까? 실
           제로 모듈의 함수/메소드가 의미하는 내용에 책임을 갖고 있어야
           합니까?
SRP Test 예



      Automobile
                               SRP 준수   SRP 위반
      start();                    ü
      stop();                     ü
      changeTires(tires []);               ü
      drive();                             ü
      wash();                              ü
      checkOil();                          ü
      getOil();                   ü
Extract Class


      두 개의 클래스가 해야 할 일을 하나의 클래스가 하고 있는 경우
      → 새로운 클래스를 만들고 관련 있는 필드와 메소드를 새로운 클래스로 옮겨라




  }   같이 변하거나, 서로 의존적인 데이터의 부분집합이 있다면,
      }   해당 데이터의 부분집합을 별도의 클래스로 분리!
Extract Class – 후보 정하기
참고서적

}   Refactoring   }   Refactoring to Pattern
Tip1: 다시 프로세스로


 Refactoring

    Identify     Find test      Break                     Make changes
                                            Write tests
 change points    points     dependencies                  and refactor




Unit Test Case가 준비되어 있지 않다면 Refactoring을 해서는 안된다
Tip2: 매일 조금씩, self inspection과 병행하여 진행




    The debt of design
Tip3: 좋은 도구 잘 활용하라

 }   Refactoring 지원 도구(IDE)
     }   Eclipse
     }   Visual Studio 계열
Tip4: 흔히 사용하는 refactoring 방법을 숙지하라

 }   Move Method
 }   Rename Class/Method
 }   Extract Method
 }   Extract Class

Más contenido relacionado

La actualidad más candente

TDD.JUnit.조금더.알기
TDD.JUnit.조금더.알기TDD.JUnit.조금더.알기
TDD.JUnit.조금더.알기Wonchang Song
 
TDD&Refactoring Day 02: TDD
TDD&Refactoring Day 02: TDDTDD&Refactoring Day 02: TDD
TDD&Refactoring Day 02: TDDSuwon Chae
 
테스트 자동화와 TDD(테스트 주도 개발방법론)
테스트 자동화와 TDD(테스트 주도 개발방법론)테스트 자동화와 TDD(테스트 주도 개발방법론)
테스트 자동화와 TDD(테스트 주도 개발방법론)KH Park (박경훈)
 
Devon 2011-b-5 효과적인 레거시 코드 다루기
Devon 2011-b-5 효과적인 레거시 코드 다루기Devon 2011-b-5 효과적인 레거시 코드 다루기
Devon 2011-b-5 효과적인 레거시 코드 다루기Daum DNA
 
우아하게 준비하는 테스트와 리팩토링 - PyCon Korea 2018
우아하게 준비하는 테스트와 리팩토링 - PyCon Korea 2018우아하게 준비하는 테스트와 리팩토링 - PyCon Korea 2018
우아하게 준비하는 테스트와 리팩토링 - PyCon Korea 2018Kenneth Ceyer
 
The Cucumber for Java
The Cucumber for JavaThe Cucumber for Java
The Cucumber for JavaJonghwa Lee
 
Test Driven Development (TDD) basic
Test Driven Development (TDD) basicTest Driven Development (TDD) basic
Test Driven Development (TDD) basicCurt Park
 
Specification By Example
Specification By ExampleSpecification By Example
Specification By ExampleJonghwa Lee
 
스프링보다 중요한 스프링 이야기
스프링보다 중요한 스프링 이야기스프링보다 중요한 스프링 이야기
스프링보다 중요한 스프링 이야기Sungchul Park
 
스프링 코어 강의 1부 - 봄 맞이 준비 운동
스프링 코어 강의 1부 - 봄 맞이 준비 운동스프링 코어 강의 1부 - 봄 맞이 준비 운동
스프링 코어 강의 1부 - 봄 맞이 준비 운동Sungchul Park
 
Tdd live spring camp 2013
Tdd live spring camp 2013Tdd live spring camp 2013
Tdd live spring camp 2013beom kyun choi
 
Clean code
Clean codeClean code
Clean codebbongcsu
 
C++ 프로젝트에 단위 테스트 도입하기
C++ 프로젝트에 단위 테스트 도입하기C++ 프로젝트에 단위 테스트 도입하기
C++ 프로젝트에 단위 테스트 도입하기Heo Seungwook
 
Java performance and trouble shooting
Java performance and trouble shootingJava performance and trouble shooting
Java performance and trouble shootingAnna Choi
 
Sonarqube 20160509
Sonarqube 20160509Sonarqube 20160509
Sonarqube 20160509영석 조
 
Java null survival guide
Java null survival guideJava null survival guide
Java null survival guideSungchul Park
 

La actualidad más candente (17)

TDD.JUnit.조금더.알기
TDD.JUnit.조금더.알기TDD.JUnit.조금더.알기
TDD.JUnit.조금더.알기
 
TDD&Refactoring Day 02: TDD
TDD&Refactoring Day 02: TDDTDD&Refactoring Day 02: TDD
TDD&Refactoring Day 02: TDD
 
TDD with JUnit 2
TDD with JUnit 2TDD with JUnit 2
TDD with JUnit 2
 
테스트 자동화와 TDD(테스트 주도 개발방법론)
테스트 자동화와 TDD(테스트 주도 개발방법론)테스트 자동화와 TDD(테스트 주도 개발방법론)
테스트 자동화와 TDD(테스트 주도 개발방법론)
 
Devon 2011-b-5 효과적인 레거시 코드 다루기
Devon 2011-b-5 효과적인 레거시 코드 다루기Devon 2011-b-5 효과적인 레거시 코드 다루기
Devon 2011-b-5 효과적인 레거시 코드 다루기
 
우아하게 준비하는 테스트와 리팩토링 - PyCon Korea 2018
우아하게 준비하는 테스트와 리팩토링 - PyCon Korea 2018우아하게 준비하는 테스트와 리팩토링 - PyCon Korea 2018
우아하게 준비하는 테스트와 리팩토링 - PyCon Korea 2018
 
The Cucumber for Java
The Cucumber for JavaThe Cucumber for Java
The Cucumber for Java
 
Test Driven Development (TDD) basic
Test Driven Development (TDD) basicTest Driven Development (TDD) basic
Test Driven Development (TDD) basic
 
Specification By Example
Specification By ExampleSpecification By Example
Specification By Example
 
스프링보다 중요한 스프링 이야기
스프링보다 중요한 스프링 이야기스프링보다 중요한 스프링 이야기
스프링보다 중요한 스프링 이야기
 
스프링 코어 강의 1부 - 봄 맞이 준비 운동
스프링 코어 강의 1부 - 봄 맞이 준비 운동스프링 코어 강의 1부 - 봄 맞이 준비 운동
스프링 코어 강의 1부 - 봄 맞이 준비 운동
 
Tdd live spring camp 2013
Tdd live spring camp 2013Tdd live spring camp 2013
Tdd live spring camp 2013
 
Clean code
Clean codeClean code
Clean code
 
C++ 프로젝트에 단위 테스트 도입하기
C++ 프로젝트에 단위 테스트 도입하기C++ 프로젝트에 단위 테스트 도입하기
C++ 프로젝트에 단위 테스트 도입하기
 
Java performance and trouble shooting
Java performance and trouble shootingJava performance and trouble shooting
Java performance and trouble shooting
 
Sonarqube 20160509
Sonarqube 20160509Sonarqube 20160509
Sonarqube 20160509
 
Java null survival guide
Java null survival guideJava null survival guide
Java null survival guide
 

Destacado

x123.tk 리팩토링
x123.tk  리팩토링x123.tk  리팩토링
x123.tk 리팩토링상옥 한
 
자라나는 소프트웨어
자라나는 소프트웨어자라나는 소프트웨어
자라나는 소프트웨어jongbhin
 
테스트 코드 삽질기 + 리팩토링
테스트 코드 삽질기 + 리팩토링테스트 코드 삽질기 + 리팩토링
테스트 코드 삽질기 + 리팩토링종훈 박
 
[NEXT] Nextgram Refactoring
[NEXT] Nextgram Refactoring[NEXT] Nextgram Refactoring
[NEXT] Nextgram RefactoringYoungSu Son
 
How (Not) to Write Testable Code
How (Not) to Write Testable CodeHow (Not) to Write Testable Code
How (Not) to Write Testable CodeThorsten Frommen
 
Refactoring tutorial
Refactoring tutorialRefactoring tutorial
Refactoring tutorialBingu Shim
 
Refactoring tutorial 1주차[refactoring 개요]
Refactoring tutorial 1주차[refactoring 개요]Refactoring tutorial 1주차[refactoring 개요]
Refactoring tutorial 1주차[refactoring 개요]bbongcsu
 
소스코드를 개선하여 효율성과 품질을 향상 시키는 방법
소스코드를 개선하여 효율성과 품질을 향상 시키는 방법소스코드를 개선하여 효율성과 품질을 향상 시키는 방법
소스코드를 개선하여 효율성과 품질을 향상 시키는 방법김진태 Jintae Kim
 
읽기 좋은 코드가 좋은코드다
읽기 좋은 코드가 좋은코드다읽기 좋은 코드가 좋은코드다
읽기 좋은 코드가 좋은코드다wonmin lee
 
고품질 Sw와 개발문화
고품질 Sw와 개발문화고품질 Sw와 개발문화
고품질 Sw와 개발문화도형 임
 
행복한 개발을 위한_테스트_케이스
행복한 개발을 위한_테스트_케이스행복한 개발을 위한_테스트_케이스
행복한 개발을 위한_테스트_케이스도형 임
 
코드의 품질 (Code Quality)
코드의 품질 (Code Quality)코드의 품질 (Code Quality)
코드의 품질 (Code Quality)ChulHui Lee
 
clean code for high quality software
clean code for high quality softwareclean code for high quality software
clean code for high quality softwareArif Huda
 
소프트웨어 테스팅
소프트웨어 테스팅소프트웨어 테스팅
소프트웨어 테스팅영기 김
 
테스트 케이스와 SW 품질
테스트 케이스와 SW 품질테스트 케이스와 SW 품질
테스트 케이스와 SW 품질도형 임
 
Refactoring - An Introduction
Refactoring - An IntroductionRefactoring - An Introduction
Refactoring - An IntroductionGiorgio Vespucci
 
Refactoring Tips by Martin Fowler
Refactoring Tips by Martin FowlerRefactoring Tips by Martin Fowler
Refactoring Tips by Martin FowlerIgor Crvenov
 
화성에서 온 개발자, 금성에서 온 기획자
화성에서 온 개발자, 금성에서 온 기획자화성에서 온 개발자, 금성에서 온 기획자
화성에서 온 개발자, 금성에서 온 기획자Yongho Ha
 

Destacado (20)

x123.tk 리팩토링
x123.tk  리팩토링x123.tk  리팩토링
x123.tk 리팩토링
 
Adv 420
Adv 420Adv 420
Adv 420
 
자라나는 소프트웨어
자라나는 소프트웨어자라나는 소프트웨어
자라나는 소프트웨어
 
테스트 코드 삽질기 + 리팩토링
테스트 코드 삽질기 + 리팩토링테스트 코드 삽질기 + 리팩토링
테스트 코드 삽질기 + 리팩토링
 
[NEXT] Nextgram Refactoring
[NEXT] Nextgram Refactoring[NEXT] Nextgram Refactoring
[NEXT] Nextgram Refactoring
 
How (Not) to Write Testable Code
How (Not) to Write Testable CodeHow (Not) to Write Testable Code
How (Not) to Write Testable Code
 
Refactoring tutorial
Refactoring tutorialRefactoring tutorial
Refactoring tutorial
 
Refactoring tutorial 1주차[refactoring 개요]
Refactoring tutorial 1주차[refactoring 개요]Refactoring tutorial 1주차[refactoring 개요]
Refactoring tutorial 1주차[refactoring 개요]
 
소스코드를 개선하여 효율성과 품질을 향상 시키는 방법
소스코드를 개선하여 효율성과 품질을 향상 시키는 방법소스코드를 개선하여 효율성과 품질을 향상 시키는 방법
소스코드를 개선하여 효율성과 품질을 향상 시키는 방법
 
읽기 좋은 코드가 좋은코드다
읽기 좋은 코드가 좋은코드다읽기 좋은 코드가 좋은코드다
읽기 좋은 코드가 좋은코드다
 
고품질 Sw와 개발문화
고품질 Sw와 개발문화고품질 Sw와 개발문화
고품질 Sw와 개발문화
 
행복한 개발을 위한_테스트_케이스
행복한 개발을 위한_테스트_케이스행복한 개발을 위한_테스트_케이스
행복한 개발을 위한_테스트_케이스
 
Code Refactoring
Code RefactoringCode Refactoring
Code Refactoring
 
코드의 품질 (Code Quality)
코드의 품질 (Code Quality)코드의 품질 (Code Quality)
코드의 품질 (Code Quality)
 
clean code for high quality software
clean code for high quality softwareclean code for high quality software
clean code for high quality software
 
소프트웨어 테스팅
소프트웨어 테스팅소프트웨어 테스팅
소프트웨어 테스팅
 
테스트 케이스와 SW 품질
테스트 케이스와 SW 품질테스트 케이스와 SW 품질
테스트 케이스와 SW 품질
 
Refactoring - An Introduction
Refactoring - An IntroductionRefactoring - An Introduction
Refactoring - An Introduction
 
Refactoring Tips by Martin Fowler
Refactoring Tips by Martin FowlerRefactoring Tips by Martin Fowler
Refactoring Tips by Martin Fowler
 
화성에서 온 개발자, 금성에서 온 기획자
화성에서 온 개발자, 금성에서 온 기획자화성에서 온 개발자, 금성에서 온 기획자
화성에서 온 개발자, 금성에서 온 기획자
 

Similar a The Introduction to Refactoring

The roadtocodecraft
The roadtocodecraftThe roadtocodecraft
The roadtocodecraftbbongcsu
 
Refactoring Tutorial 1주차[ Refactoring 개요]
Refactoring  Tutorial 1주차[ Refactoring 개요]Refactoring  Tutorial 1주차[ Refactoring 개요]
Refactoring Tutorial 1주차[ Refactoring 개요]Bingu Shim
 
프로젝트 Xxx에 적용하고 싶은 개발방법
프로젝트 Xxx에 적용하고 싶은 개발방법프로젝트 Xxx에 적용하고 싶은 개발방법
프로젝트 Xxx에 적용하고 싶은 개발방법도형 임
 
[Dev rookie]designpattern
[Dev rookie]designpattern[Dev rookie]designpattern
[Dev rookie]designpattern대영 노
 
Javascript refactoring workshop
Javascript refactoring workshopJavascript refactoring workshop
Javascript refactoring workshopJaehoon Oh
 
[NDC12] 변화량 분석을 중심으로 한 저비용 고효율의 지속가능한 코드퀄리티 관리법 - 송창규
[NDC12] 변화량 분석을 중심으로 한 저비용 고효율의 지속가능한 코드퀄리티 관리법 - 송창규[NDC12] 변화량 분석을 중심으로 한 저비용 고효율의 지속가능한 코드퀄리티 관리법 - 송창규
[NDC12] 변화량 분석을 중심으로 한 저비용 고효율의 지속가능한 코드퀄리티 관리법 - 송창규ChangKyu Song
 
C Language II
C Language IIC Language II
C Language IISuho Kwon
 
개발이 테스트를 만났을 때(Shift left testing)
개발이 테스트를 만났을 때(Shift left testing)개발이 테스트를 만났을 때(Shift left testing)
개발이 테스트를 만났을 때(Shift left testing)SangIn Choung
 
GraphQL in Action - REST와 이별할 때 생각해야 하는 것들
GraphQL in Action - REST와 이별할 때 생각해야 하는 것들GraphQL in Action - REST와 이별할 때 생각해야 하는 것들
GraphQL in Action - REST와 이별할 때 생각해야 하는 것들Kivol
 
자동화된 Test Case의 효과
자동화된 Test Case의 효과자동화된 Test Case의 효과
자동화된 Test Case의 효과도형 임
 
Patterns for effectviely documenting frameworks
Patterns for effectviely documenting frameworksPatterns for effectviely documenting frameworks
Patterns for effectviely documenting frameworksSunuk Park
 
테스트 자동화의 원칙
테스트 자동화의 원칙테스트 자동화의 원칙
테스트 자동화의 원칙codevania
 
프로젝트 관리 및 지켜야 할 사항들
프로젝트 관리 및 지켜야 할 사항들프로젝트 관리 및 지켜야 할 사항들
프로젝트 관리 및 지켜야 할 사항들Lee Geonhee
 
카사 공개세미나1회 W.E.L.C.
카사 공개세미나1회  W.E.L.C.카사 공개세미나1회  W.E.L.C.
카사 공개세미나1회 W.E.L.C.Ryan Park
 
DevRookie 리펙터링.pptx
DevRookie 리펙터링.pptxDevRookie 리펙터링.pptx
DevRookie 리펙터링.pptxMUUMUMUMU
 
Testing & refactoring
Testing & refactoringTesting & refactoring
Testing & refactoringLim Hosung
 
분석과 설계
분석과 설계분석과 설계
분석과 설계Haeil Yi
 
HolubOnPatterns/chapter2_2
HolubOnPatterns/chapter2_2HolubOnPatterns/chapter2_2
HolubOnPatterns/chapter2_2SeungHyun Hwang
 

Similar a The Introduction to Refactoring (20)

The roadtocodecraft
The roadtocodecraftThe roadtocodecraft
The roadtocodecraft
 
Refactoring Tutorial 1주차[ Refactoring 개요]
Refactoring  Tutorial 1주차[ Refactoring 개요]Refactoring  Tutorial 1주차[ Refactoring 개요]
Refactoring Tutorial 1주차[ Refactoring 개요]
 
프로젝트 Xxx에 적용하고 싶은 개발방법
프로젝트 Xxx에 적용하고 싶은 개발방법프로젝트 Xxx에 적용하고 싶은 개발방법
프로젝트 Xxx에 적용하고 싶은 개발방법
 
[Dev rookie]designpattern
[Dev rookie]designpattern[Dev rookie]designpattern
[Dev rookie]designpattern
 
Javascript refactoring workshop
Javascript refactoring workshopJavascript refactoring workshop
Javascript refactoring workshop
 
[NDC12] 변화량 분석을 중심으로 한 저비용 고효율의 지속가능한 코드퀄리티 관리법 - 송창규
[NDC12] 변화량 분석을 중심으로 한 저비용 고효율의 지속가능한 코드퀄리티 관리법 - 송창규[NDC12] 변화량 분석을 중심으로 한 저비용 고효율의 지속가능한 코드퀄리티 관리법 - 송창규
[NDC12] 변화량 분석을 중심으로 한 저비용 고효율의 지속가능한 코드퀄리티 관리법 - 송창규
 
C Language II
C Language IIC Language II
C Language II
 
개발이 테스트를 만났을 때(Shift left testing)
개발이 테스트를 만났을 때(Shift left testing)개발이 테스트를 만났을 때(Shift left testing)
개발이 테스트를 만났을 때(Shift left testing)
 
GraphQL in Action - REST와 이별할 때 생각해야 하는 것들
GraphQL in Action - REST와 이별할 때 생각해야 하는 것들GraphQL in Action - REST와 이별할 때 생각해야 하는 것들
GraphQL in Action - REST와 이별할 때 생각해야 하는 것들
 
자동화된 Test Case의 효과
자동화된 Test Case의 효과자동화된 Test Case의 효과
자동화된 Test Case의 효과
 
Patterns for effectviely documenting frameworks
Patterns for effectviely documenting frameworksPatterns for effectviely documenting frameworks
Patterns for effectviely documenting frameworks
 
테스트 자동화의 원칙
테스트 자동화의 원칙테스트 자동화의 원칙
테스트 자동화의 원칙
 
Working with code
Working with codeWorking with code
Working with code
 
프로젝트 관리 및 지켜야 할 사항들
프로젝트 관리 및 지켜야 할 사항들프로젝트 관리 및 지켜야 할 사항들
프로젝트 관리 및 지켜야 할 사항들
 
카사 공개세미나1회 W.E.L.C.
카사 공개세미나1회  W.E.L.C.카사 공개세미나1회  W.E.L.C.
카사 공개세미나1회 W.E.L.C.
 
DevRookie 리펙터링.pptx
DevRookie 리펙터링.pptxDevRookie 리펙터링.pptx
DevRookie 리펙터링.pptx
 
Testing & refactoring
Testing & refactoringTesting & refactoring
Testing & refactoring
 
분석과 설계
분석과 설계분석과 설계
분석과 설계
 
HolubOnPatterns/chapter2_2
HolubOnPatterns/chapter2_2HolubOnPatterns/chapter2_2
HolubOnPatterns/chapter2_2
 
EC 789
EC 789EC 789
EC 789
 

The Introduction to Refactoring

  • 2. SW 프로젝트에서 개발자를 괴롭히는 악당들이 있습니다
  • 3. 악당1. 시도 때도 없는 요구사항 변경
  • 4. 악당2. 말도 안 되는 몰상식한 일정(추정) 월 화 수 목 금 금 금 월 화 수 목 금 금 금 월 화 수 목 금 금 금 월 화 수 목 금 금 금 월 화 수 목 금 금 금 월 화 수 목 금 금 금 월 화 수 목 금 금 금 월 화 수 목 금 금 금 월 화 수 목 금 금 금 월 화 수 목 금 금 금 월 화 수 목 금 금 금 월 화 수 목 금 금 금 월 화 수 목 금 금 금 월 화 수 목 금 금 금 월 화 수 목 금 금 금 월 화 수 목 금 금 금 월 화 수 목 금 금 금 월 화 수 목 금 금 금
  • 6. SW 프로젝트 폭주의 결과로… 퇴사를 합니다
  • 7. 이렇게 되면 우리 코드에 무슨 일이 생길까요?
  • 8. 이렇게 됩니다 “얼마 못 사시겠습니다”
  • 10. 이러한 문제를 해결해보고자 하는 공학적 접근법 Reengineering 요즘은 Refactoring 이라고도 합니다
  • 11. 물론 Refactoring이 근본 해결책은 아닙니다
  • 12. Refactoring은 여러 대안 중 하나입니다
  • 13. Reengineering vs Refactoring 잠시 동안 살 수 없어요 살면서 할 수 있어요
  • 14. Reengineering vs Refactoring정의 Reengineering } Chikofsky and Cross, "The examination and alteration of a system to reconstitute it in a new form". } the modification of a software system that takes place after it has been reverse engineered, generally to add new functionality, or to correct errors. Refactoring } Martin Fowler, "disciplined technique for restructuring an existing body of code, altering its internal structure without changing its external behavior", } undertaken in order to improve some of the nonfunctional attributes of the software } Tiny change in a computer program's source code that does NOT modify its functional requirements.
  • 15. Keyword 차이 Reegineering Refactoring Reverse Engineering Internal structure (legacy code analysis) Readability Restructuring decrease complexity Tiny change (Fine-grained structure) Maintainability extensibility New functionality Non functionality
  • 16. 프로세스 차이 Reengineering Legacy code To be Restructuring Refactoring System Test analysis architecture Refactoring Identify Find test Break Make changes Write tests change points points dependencies and refactor
  • 17. 구조를 왜 바꾸려는 걸까요? “코드가 자꾸 늙기 때문이죠” 스파게티 코드 다수 존재 Feature enhance, bug fixing으로 인한 코드 수정 어려움 미흡한 영향평가로 new bug 등장 코드 수정 비용 증가
  • 18. 언제, 어떻게 Refactoring을 해야 하는가? } 틈틈이 계속 } 리팩토링 자체가 목적이 아니라, 다른 것을 하기 위해 리팩토링을 하는 것이고, 리팩토링은 그 다른 것을 하는데 도움을 준다. } 삼진 규칙 } 세 번째로 비슷한 것을 하게 되면 리팩토링을 한다 } 기능을 추가할 때, 버그를 수정할 때 } 코드에 대한 이해를 돕기 위해서 } 코드 검토 시 } 고수준의 의견을 얻을 수 있음 } 준비가 많이 필요함 } 언제 리팩토링을 하지 말아야 하는가? } 코드를 처음부터 작성 하는 게 나을 정도로 엉망인 경우 } 현재의 코드가 작동하지 않을 경우 } 마감일에 가까울 경우
  • 19. 특히… 구린내(Bad Smell)가 나면 Refactoring을 합니다
  • 20. 구린내(Bad Smell) } 구린내(Bad Smell)는 코드에 잠재된 문제에 대한 경 고 표시 } 대표적 냄새 } Duplicated code } Long method } Long parameter list } Large class
  • 21. Duplicated Code } 가장 많이 발생하는 냄새 } 해결책 } 하나의 클래스에서 중복 } ExtractMethod } 두 형제 클래스에서 중복 } ExtractMethod -> Pull Up Field or Pull Up Method - > Form Template Method
  • 22. Extract Method void printOwing() { printBanner(); //print details System.out.println ("name: " + _name); System.out.println ("amount " + getOutstanding()); }
  • 23. Extract Method (Contd.) void printOwing() { printBanner(); printDetails(getOutstanding()); } void printDetails (double outstanding) { System.out.println ("name: " + _name); System.out.println ("amount " + outstanding); }
  • 24. Duplicated Code Smell } same expression in two sibling subclasses Refactor } Extract method in both classes. } Pull up field.
  • 25. Pull Up Field } Two subclasses have the same field. } Move the field to the superclass.
  • 26. Pull Up Field (Contd.)
  • 27. Duplicated Code Smell } Code is similar but not the same Refactor: } Use Extract Method to separate the similar bits from the different bits. } Use Form Template Method.
  • 28. Form template method } 각각의 서브클래스에, 동일한 순서로 비슷한 단 계를 행하지만, 단계가 완전히 같지는 않은 두 메소드가 있다면, 그 단계를 동일한 시그너처를 가진 메소드로 만들어라 } 이렇게 하면 원래의 두 메소드는 서로 같아지므 로, 수퍼클래스로 올릴 수 있다.
  • 30. Long method } Object program having short methods live best and longest. } Little methods are the most valuable. } Longer methods are difficult to understand.
  • 31. Extract Method } Cyclomatic Complexity } Essential Complexity } Control Flow
  • 32. Long Parameter List } Smell } A method call requires passing long list of parameters. } Refactor } Use Introduce Parameter Object.
  • 33. Introduce Parameter Object 자연스럽게 몰려다니는 파라미터 그룹을 가지고 있다면 → 그것들을 객체로 바꾸어라 } 같이 넘겨지는 경향이 있는 특별한 그룹의 파라미터에 대해 } -> 데이터 덩어리 } -> 객체형태로 묶일 수 있음 } 부가 효용 } 새로 생긴 객체에 들어가야 할 메소드가 쉽게 눈에 띔 } 이에 따라, 중복을 효과적으로 제거할 수 있음
  • 34. Large Class } Too many responsibilities } Broken SRP } SRP: Every class should have a single responsibility, and that responsibility should be entirely encapsulated by the class. All its services should be narrowly aligned with that responsibility.
  • 35. SRP Test 단일책임원칙(Single Responsibility Principle) SRP •클래스가 한가지 책임만 가져야 한다는 원칙 •클래스나 모듈을 변경할 이유가 하나 뿐이어야 함 •큰 클래스 è 작은 클래스 여럿 작은 클래스와 협력해 시스템에 필요한 동작 수행 ____________가 스스로 ___________ 한다. 각 줄의 첫 번째 공백에 모듈명을 적습니다. 두 번째 공백에 모듈의 메소드/함수 중 하나를 적습니다. 모듈의 모든 함수/메소드마다 이 를 수행합니다. 각 줄을 소리 내어 읽습니다. 읽은 내용을 이해할 수 있습니까? 실 제로 모듈의 함수/메소드가 의미하는 내용에 책임을 갖고 있어야 합니까?
  • 36. SRP Test 예 Automobile SRP 준수 SRP 위반 start(); ü stop(); ü changeTires(tires []); ü drive(); ü wash(); ü checkOil(); ü getOil(); ü
  • 37. Extract Class 두 개의 클래스가 해야 할 일을 하나의 클래스가 하고 있는 경우 → 새로운 클래스를 만들고 관련 있는 필드와 메소드를 새로운 클래스로 옮겨라 } 같이 변하거나, 서로 의존적인 데이터의 부분집합이 있다면, } 해당 데이터의 부분집합을 별도의 클래스로 분리!
  • 38. Extract Class – 후보 정하기
  • 39. 참고서적 } Refactoring } Refactoring to Pattern
  • 40. Tip1: 다시 프로세스로 Refactoring Identify Find test Break Make changes Write tests change points points dependencies and refactor Unit Test Case가 준비되어 있지 않다면 Refactoring을 해서는 안된다
  • 41. Tip2: 매일 조금씩, self inspection과 병행하여 진행 The debt of design
  • 42. Tip3: 좋은 도구 잘 활용하라 } Refactoring 지원 도구(IDE) } Eclipse } Visual Studio 계열
  • 43. Tip4: 흔히 사용하는 refactoring 방법을 숙지하라 } Move Method } Rename Class/Method } Extract Method } Extract Class