Computer Basics/Design Pattern
클린코드와 리팩토링
Bumang
2023. 10. 17. 08:59
클린코드
클린코드란, 가독성이 높은 코드를 말한다.
리팩토링
프로그램의 외부 동작은 그대로 둔 채, 내부의 코드를 정리하면서 개선하는 것을 말함
보통 코드를 유지보수하면서 동시에 클린 코드로 전환하는 것 모두 리팩토링에 해당된다.
리팩토링이 필요한 코드는?
- 중복 코드
- 긴 메소드
- 거대한 클래스
- Switch 문
- 절차지향으로 구현한 코드
리팩토링 예제
1. 범용적인 이름을 쓰지않고 구체적인 이름을 쓴다.
// 수정 전
public int getFoodPrice(int arg1, int arg2) {
return arg1 * arg2;
}
// 수정 후
public int getTotalFoodPrice(int price, int quantity) {
return price * quantity;
}
2. 중복 사용되는 코드는 변수로 지정하여 이름을 붙인다.
// 수정 전
public int getTotalPrice(int price, int quantity, double discount) {
return (int) ((price * quantity) * (price * quantity) * (discount /100));
}
// 수정 후
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);
}
return (int) ((price * quantity) * (price * quantity) * (discount /100));
수정 전에 price * quantity가 계속 중복된다.
return (int) (totalPriceQuantity - getDiscountPrice(discount, totalPriceQuantity))
이를 변수로 만들어 어떤 항목을 계산하고 있는지 명확히 전달한다.
3. 함수는 특정한 동작을 수행하니 동사로, 클래스나 속성은 명사로 이름 짓자
클래스나 속성이 어떠한 대상을 나타낸다면, 함수는 그 대상을 받아 특정한 동작을 수행한다고 예상할 수 있다.
이를 나타내기 위해 클래스나 속성은 명사로, 함수는 동사로 네이밍하는 것이 좋다.
public class Account {
//
private int amount;
public static int transferMoney(int money){
amount -= money;
};
}
Account.transferMoney(1000);
4. 함수 작성 요령
- 함수는 최대한 작게 만든다.
- 한 가지의 기능만 하도록 한다.
- 함수의 인수도 적을수록 좋다.
- 명령과 조회를 분리한다.
5. 흐름제어 만들기(Making control flow easy to read)
1. 왼쪽에는 변수를, 오른쪽에는 상수를 두고 비교
if(length >= 10)
while(bytes_received < bytest_expected)
2. 부정이 아닌 긍정을 다루자
if( a == b ) { // a!=b는 부정
// same
} else {
// different
}
6. 적절한 추상화
추상화 시켜서 표현할 수 있다면 적정한 선에서 복잡성을 줄인다.