CS(Computer Science)/Software Engineering

클린 코드, 리팩토링

환성 2023. 1. 5. 17:56
728x90

클린코드(Clean Code)

  • 가독성이 높은 코드
  • 얼마나 잘 읽히고 코드가 지저분하지 않고 정리된 코드인지를 보여줘야 한다.
  • 가독성을 높이기 위해서는 다음과 같이 구현해야 한다.
    • 네이밍이 잘 되어있어야 한다
    • 오류 X
    • 중복 X
    • 의존성을 최대한 줄여야 한다.
    • 클래스 혹은 메소드가 한 가지 일만 처리해야 한다.
// 덧셈 기능 함수
public int ABC(int a, int b){
	return a + b;
}
// 뺼셈 기능 함수
public int BAA(int a, int b){
	return a - b;
}




// 수정 후
// 덧셈 기능 함수
public int sum(int a, int b){
	return a + b;
}

// 뺼셈 기능 함수
public int sub(int a, int b){
	return a - b;
}

위 코드는 두가지 문제점을 가지고 있다.

첫째, 함수 네이밍이 문제다. 다른 개발자나 외부 사람이 봐도 무슨 역할을 하는 함수인지 알 수 있도록 해야 한다. 예로 덧셈 기능 함수면 sum을 사용한다던가, 뺄셈이면 sub같은 이름을 사용해야한다.

 

둘째, 함수와 함수 사이의 간격이다. 여러 함수가 존재할 때 간격을 두지 않으면 시작과 끝을 구분하는 것이 힘들고 가독성이 떨어진다.

 

리팩토링(Refactoring)

  • 프로그램의 외부 동작은 그대로 둔 채, 내부의 코드를 정리하면서 개선하는 것
  • 소프트웨어에 새로운 기능을 추가할 때 필요하다
  • 코드의 가독성을 높이고, 유지보수에 큰 도움이 된다
  • 리팩토링이 필요한 코드
    • 중복 코드
    • 긴 메소드
    • 거대한 클래스
    • Switch 문
    • 절차지향으로 구현한 코드
// 수정 전
public int getFoodPrice(int arg1, int arg2){
	return arg1 * arg2;
}

// 수정 후
public int getTotalFoodPrice(int price, int quality){
	return price * quality;
}


// 수정 전 - price * quantity가 중복
public int getTotalPrice(int price, int quantity, double discount){
	return (int) ((price * quantity)) * (price * quantity) * (discount/100));
}


// 수정 후 - private으로 함수 하나를 더 만들어 사용
public int getTotalPrice(int price, int quantity, double discount){
	int totalPriceQuantity = price * quantity;
	return (int) ((totalQuantity - getDiscountPrice(discount, totalPriceQuantity))
}

private double getDiscountPrice(double discount, int totalPriceQuantity){
	return totalPriceQuantity * (discount/100);
}


// 한 번 더 수정 - totalPriceQuantity를 getter 메소드로 추출가능
public int getFoodPriceToPay(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);
}

private int getTotalPriceQuantity(int price, int quantity){
	return price * quantity;
}

 

주석 작성

  • 주석 작성은 남들이 알아볼 수 있게 적자
  • 코드만 보고 이해하되 도저히 이해가 가지 않을 떄만 작성
  • 최대한 주석 작성을 자제
  • Todo 주석을 작성하여 어디까지 했는지, 내일은 무엇을 할지 정해놓는게 좋다.

 

예외 처리

  • try-catch문을 사용하여 예외처리를 한다
  • Null을 반환하는걸 지양하고 빈 배열이나 0과 같은 값을 반환하는게 좋다.
  • 예외 발생은 무조건 throw 해주자
try{
	// 에러 발생 코드
    throw new Exception(); // 강제 에러 출력
}catch(Exception e){
	// 에러 시 수행
    e.printStackTrace(); // 오류 출력
    throw e; // 최상위 클래스가 아니라면 던져준다.
}finally{
	// 무조건 수행
}

 

 

 

출처:
https://gyoogle.dev/blog/computer-science/software-engineering/Clean%20Code%20&%20Refactoring.html

'CS(Computer Science) > Software Engineering' 카테고리의 다른 글

써드 파티(3rd party)  (0) 2023.01.08
데브옵스(DevOps)  (0) 2023.01.07
애자일(Agile)  (0) 2023.01.07
테스트 주도 개발 : TDD(Test Driven Development)  (0) 2023.01.05