SlideShare a Scribd company logo
1 of 8
Page 1
예제로 맛보는 리펙토링
by 이은숙
Page 2
음식값을 계산해주세요 !
단순히 가격과 수량을 통해 계산하는 단순한 프로그램을 시작으로 어떻게 리펙토링
을 적용할 수 있는지 짚어보자 .
public int getFoodPrice(int arg1, int arg2) {
return arg1 * arg2;
}
public int getTotalFoodPrice(int price, int quantity) {
return price * quantity;
}
1. 함수명은 좀더 직관적이게 수정한다 .
2. 변수명은 기존에 모호한 이름에서 뜻에 맞게 수정한다 .
eclipse 단축키 Tip
이름 변경 : 변경하려는 함수명 ( 변수명 ) 에 커서를 옮긴 후 Shift + Alt 를 동시에 누른면서 R 을 누르면 블록 표시가 나
타나면 알맞게 수정 후 enter 를 누르면 참조된 함수명 ( 변수명 ) 까지 일괄적으로 수정된다 .
Page 3
음식값을 할인해주세요 !
public int getTotalFoodPrice(int price, int quantity, double discount) {
return (int) ((price * quantity) - (price * quantity) * (discount / 100));
}
1. 가격과 수량을 계산하는 로직을 변수로 추출한다 .
2. 할일율을 계산하는 로직을 함수로 추출한다 .
eclipse 단축키 Tip
변수 추출 : 추출하려는 로직에 블럭처리한 다음 Shift + Alt 를 동시에 누른면서 L 을 누르면 팝업창이 뜨면 알맞은 변수명
을 넣고 OK 하면 같은 로직까지 찾아서 일괄적으로 변수로 추출된다 .
메소드 추출 : 추출하려는 로직에 블럭처리한 다음 Shift + Alt 를 동시에 누른면서 M 을 누르면 팝업창이 뜨면 알맞은 메소
드명을 넣고 OK 하면 같은 로직까지 찾아서 일괄적으려 메소드로 추출된다 .
public int getTotalFoodPrice(int price, int quantity, double discount) {
int totalPriceQuantity = price * quantity;
return (int) (totalPriceQuantity - getDiscountPrice(discount, totalPriceQuantity));
}
private double getDiscountPrice(double discount, int totalPriceQuantity) {
return totalPriceQuantity * (discount / 100);
}
Page 4
음식값을 할인해주세요 !
3. 변수로 추출한 totalPriceQuantity 를 다시 메서드로 추출하여 변경한다 .
4. getTotalFoodPrice 도 지불하려는 의미로 직관적이게 다시한번 변경한다 .
public int getTotalFoodPrice(int price, int quantity, double discount) {
int totalPriceQuantity = price * quantity;
return (int) (totalPriceQuantity - getDiscountPrice(discount, totalPriceQuantity));
}
private double getDiscountPrice(double discount, int totalPriceQuantity) {
return totalPriceQuantity * (discount / 100);
}
public int getFoodPriceToPay(int price, int quantity, double discount) {
int totalPriceQuantity = getTotalPriceQuantity(price, quantity);
return (int) (totalPriceQuantity - getDiscountPrice(discount, totalPriceQuantity));
}
private int getTotalPriceQuantity(int price, int quantity) {
return price * quantity;
}
……
Page 5
신용카드로 결제할게요 !
1. 신용카드 코드 데이터 뿐만 아니라 카드에 따른 할인율을 확장성을 고려하여
creditCardCode 를 객체로 변경한다 .
2. 매직넘버를 상수화 한다 .
public int getFoodPriceToPayByCreditcard(int price, int quantity, String creditCardCard)
throws Exception {
if (“01".equals(creditCardCard)) {
return getFoodPriceToPay(price, quantity, 10);
} else if ("02".equals(creditCardCard)) {
return getFoodPriceToPay(price, quantity, 20);
} else {
throw new Exception("It is not exist credit card");
}
}
Page 6
public class CreditCard {
private String creditCardCode;
private double discountPercent;
public String getCreditCardCode() {
return creditCardCode;
}
public void setCreditCardCode(String creditCardCode) {
this.creditCardCode = creditCardCode;
}
public double getDiscountPercent() {
return discountPercent;
}
public void setDiscountPercent(double discountPercent) {
this.discountPercent = discountPercent;
}
}
eclipse 단축키 Tip
setter geetter method 생성 : 필요한 필드를 미리 선언한 다음 Shift + Alt 를 동시에 누른면서 S 을 누르면 메뉴창이 뜨
면 Genereate Getters and Setters 를 선택한 후 팝업창이 뜨면 생성하려는 메소드를 선택한 후 OK 하면 자동으로 생성된다 .
신용카드로 결제할게요 !
Page 7
private static final String H_CARD = "01";
private static final String S_CARD = "02";
public int getFoodPriceToPayByCreditcard(int price, int quantity, CreditCard creditCard)
throws Exception {
if (H_CARD.equals(creditCard.getCreditCardCode())) {
return getFoodPriceToPay(price, quantity, creditCard.getDiscountPercent());
} else if (S_CARD.equals(creditCard.getCreditCardCode())) {
return getFoodPriceToPay(price, quantity, creditCard.getDiscountPercent());
} else {
throw new Exception("It is not exist credit card");
}
}
3. 카드 추가에 따른 if 구문이 늘어날 수 있으므로 알고리즘화 한다 .
eclipse 단축키 Tip
매직넘버 상수 추출 : 추출하려는 상수에 블럭처리한 다음 Shift + Alt 를 동시에 누른면서 T 을 누르면 메뉴창이 뜨면
Extras Constant… 를 선택한 후 팝업창이 뜨면 생성하려는 상수명을 입력한 후 OK 하면 자동으로 생성된다 .
신용카드로 결제할게요 !
Page 8
private static final String H_CARD = "01";
private static final String S_CARD = "02";
public int getFoodPriceToPayByCreditcard(int price, int quantity, CreditCard creditCard)
throws Exception {
List cardCodeList = Arrays.asList(new String [] {H_CARD, S_CARD });
if (cardCodeList.contains(creditCard.getCreditCardCode())) {
return getFoodPriceToPay(price, quantity, creditCard.getDiscountPercent());
} else {
throw new Exception("It is not exist credit card");
}
}
신용카드로 결제할게요 !

More Related Content

Featured

2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by HubspotMarius Sescu
 
Everything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTEverything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTExpeed Software
 
Product Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsProduct Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsPixeldarts
 
How Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthHow Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthThinkNow
 
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfAI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfmarketingartwork
 
PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024Neil Kimberley
 
Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)contently
 
How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024Albert Qian
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsKurio // The Social Media Age(ncy)
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Search Engine Journal
 
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summarySpeakerHub
 
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd Clark Boyd
 
Getting into the tech field. what next
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next Tessa Mero
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentGoogle's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentLily Ray
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best PracticesVit Horky
 
The six step guide to practical project management
The six step guide to practical project managementThe six step guide to practical project management
The six step guide to practical project managementMindGenius
 
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...RachelPearson36
 

Featured (20)

2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot
 
Everything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTEverything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPT
 
Product Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsProduct Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage Engineerings
 
How Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthHow Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental Health
 
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfAI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
 
Skeleton Culture Code
Skeleton Culture CodeSkeleton Culture Code
Skeleton Culture Code
 
PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024
 
Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)
 
How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie Insights
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024
 
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary
 
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd
 
Getting into the tech field. what next
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentGoogle's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search Intent
 
How to have difficult conversations
How to have difficult conversations How to have difficult conversations
How to have difficult conversations
 
Introduction to Data Science
Introduction to Data ScienceIntroduction to Data Science
Introduction to Data Science
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best Practices
 
The six step guide to practical project management
The six step guide to practical project managementThe six step guide to practical project management
The six step guide to practical project management
 
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
 

예제로 맛보는 리펙토링 연습

  • 1. Page 1 예제로 맛보는 리펙토링 by 이은숙
  • 2. Page 2 음식값을 계산해주세요 ! 단순히 가격과 수량을 통해 계산하는 단순한 프로그램을 시작으로 어떻게 리펙토링 을 적용할 수 있는지 짚어보자 . public int getFoodPrice(int arg1, int arg2) { return arg1 * arg2; } public int getTotalFoodPrice(int price, int quantity) { return price * quantity; } 1. 함수명은 좀더 직관적이게 수정한다 . 2. 변수명은 기존에 모호한 이름에서 뜻에 맞게 수정한다 . eclipse 단축키 Tip 이름 변경 : 변경하려는 함수명 ( 변수명 ) 에 커서를 옮긴 후 Shift + Alt 를 동시에 누른면서 R 을 누르면 블록 표시가 나 타나면 알맞게 수정 후 enter 를 누르면 참조된 함수명 ( 변수명 ) 까지 일괄적으로 수정된다 .
  • 3. Page 3 음식값을 할인해주세요 ! public int getTotalFoodPrice(int price, int quantity, double discount) { return (int) ((price * quantity) - (price * quantity) * (discount / 100)); } 1. 가격과 수량을 계산하는 로직을 변수로 추출한다 . 2. 할일율을 계산하는 로직을 함수로 추출한다 . eclipse 단축키 Tip 변수 추출 : 추출하려는 로직에 블럭처리한 다음 Shift + Alt 를 동시에 누른면서 L 을 누르면 팝업창이 뜨면 알맞은 변수명 을 넣고 OK 하면 같은 로직까지 찾아서 일괄적으로 변수로 추출된다 . 메소드 추출 : 추출하려는 로직에 블럭처리한 다음 Shift + Alt 를 동시에 누른면서 M 을 누르면 팝업창이 뜨면 알맞은 메소 드명을 넣고 OK 하면 같은 로직까지 찾아서 일괄적으려 메소드로 추출된다 . public int getTotalFoodPrice(int price, int quantity, double discount) { int totalPriceQuantity = price * quantity; return (int) (totalPriceQuantity - getDiscountPrice(discount, totalPriceQuantity)); } private double getDiscountPrice(double discount, int totalPriceQuantity) { return totalPriceQuantity * (discount / 100); }
  • 4. Page 4 음식값을 할인해주세요 ! 3. 변수로 추출한 totalPriceQuantity 를 다시 메서드로 추출하여 변경한다 . 4. getTotalFoodPrice 도 지불하려는 의미로 직관적이게 다시한번 변경한다 . public int getTotalFoodPrice(int price, int quantity, double discount) { int totalPriceQuantity = price * quantity; return (int) (totalPriceQuantity - getDiscountPrice(discount, totalPriceQuantity)); } private double getDiscountPrice(double discount, int totalPriceQuantity) { return totalPriceQuantity * (discount / 100); } public int getFoodPriceToPay(int price, int quantity, double discount) { int totalPriceQuantity = getTotalPriceQuantity(price, quantity); return (int) (totalPriceQuantity - getDiscountPrice(discount, totalPriceQuantity)); } private int getTotalPriceQuantity(int price, int quantity) { return price * quantity; } ……
  • 5. Page 5 신용카드로 결제할게요 ! 1. 신용카드 코드 데이터 뿐만 아니라 카드에 따른 할인율을 확장성을 고려하여 creditCardCode 를 객체로 변경한다 . 2. 매직넘버를 상수화 한다 . public int getFoodPriceToPayByCreditcard(int price, int quantity, String creditCardCard) throws Exception { if (“01".equals(creditCardCard)) { return getFoodPriceToPay(price, quantity, 10); } else if ("02".equals(creditCardCard)) { return getFoodPriceToPay(price, quantity, 20); } else { throw new Exception("It is not exist credit card"); } }
  • 6. Page 6 public class CreditCard { private String creditCardCode; private double discountPercent; public String getCreditCardCode() { return creditCardCode; } public void setCreditCardCode(String creditCardCode) { this.creditCardCode = creditCardCode; } public double getDiscountPercent() { return discountPercent; } public void setDiscountPercent(double discountPercent) { this.discountPercent = discountPercent; } } eclipse 단축키 Tip setter geetter method 생성 : 필요한 필드를 미리 선언한 다음 Shift + Alt 를 동시에 누른면서 S 을 누르면 메뉴창이 뜨 면 Genereate Getters and Setters 를 선택한 후 팝업창이 뜨면 생성하려는 메소드를 선택한 후 OK 하면 자동으로 생성된다 . 신용카드로 결제할게요 !
  • 7. Page 7 private static final String H_CARD = "01"; private static final String S_CARD = "02"; public int getFoodPriceToPayByCreditcard(int price, int quantity, CreditCard creditCard) throws Exception { if (H_CARD.equals(creditCard.getCreditCardCode())) { return getFoodPriceToPay(price, quantity, creditCard.getDiscountPercent()); } else if (S_CARD.equals(creditCard.getCreditCardCode())) { return getFoodPriceToPay(price, quantity, creditCard.getDiscountPercent()); } else { throw new Exception("It is not exist credit card"); } } 3. 카드 추가에 따른 if 구문이 늘어날 수 있으므로 알고리즘화 한다 . eclipse 단축키 Tip 매직넘버 상수 추출 : 추출하려는 상수에 블럭처리한 다음 Shift + Alt 를 동시에 누른면서 T 을 누르면 메뉴창이 뜨면 Extras Constant… 를 선택한 후 팝업창이 뜨면 생성하려는 상수명을 입력한 후 OK 하면 자동으로 생성된다 . 신용카드로 결제할게요 !
  • 8. Page 8 private static final String H_CARD = "01"; private static final String S_CARD = "02"; public int getFoodPriceToPayByCreditcard(int price, int quantity, CreditCard creditCard) throws Exception { List cardCodeList = Arrays.asList(new String [] {H_CARD, S_CARD }); if (cardCodeList.contains(creditCard.getCreditCardCode())) { return getFoodPriceToPay(price, quantity, creditCard.getDiscountPercent()); } else { throw new Exception("It is not exist credit card"); } } 신용카드로 결제할게요 !