# 코드 가독성 및 유지 관리 기능 향상

공동 파일럿 채팅은 코드를 더 쉽게 이해하고 유지 관리할 방법을 제안할 수 있습니다.

가독성이 낮은 코드는 다른 개발자가 유지 관리하고 확장하기 어렵습니다. 공동 파일럿 채팅은 여러 가지 방법으로 사용자에게 도움이 될 수 있습니다. 예를 들면 다음과 같습니다.

* [변수 이름 개선 제안](#improving-variable-names)
* [순차적 조건부 검사 방지](#avoiding-sequential-conditional-checks)
* [중첩된 논리 감소](#reducing-nested-logic)
* [큰 메서드를 더 작고 읽기 쉬운 메서드로 분할](#splitting-up-large-methods)

코드 문서화는 코드의 유지 관리를 개선하는 또 다른 방법입니다. 공동 파일럿 채팅을 사용하여 코드에 유용한 주석을 추가하는 방법에 대한 자세한 내용은 [코드 문서화](/ko/copilot/copilot-chat-cookbook/documenting-code)의 예제 프롬프트를 참조하세요.

> \[!NOTE] 이 문서에 표시된 응답은 예제입니다. 공동 파일럿 채팅 응답은 비결정적이므로 여기에 표시된 응답과 다른 응답을 얻을 수 있습니다.

## 변수 이름 개선

설명이 포함된 변수 이름과 매개 변수 이름을 사용하면 해당 용도를 더 쉽게 이해할 수 있습니다.

### 예제 시나리오

이 JavaScript 코드는 사용자의 나이에 대한 메시지를 콘솔에 기록합니다. 추상 매개 변수 이름을 사용하면 코드의 용도를 이해하기가 어렵습니다.

```javascript id=log-persons-age
function logPersonsAge(a, b, c) {
  if (c) {
    console.log(a + " is " + b + " years old.");
  } else {
    console.log(a + " does not want to reveal their age.");
  }
}
```

### 예시 프롬프트

편집기에서 변경할 함수를 선택한 다음, 공동 파일럿 채팅에게 다음을 요청하세요.

```copilot copy prompt ref=log-persons-age
Improve the variable names in this function
```

### 예제 응답

Copilot는 설명적인 변수 이름을 제안합니다.

```javascript
function logPersonAge(name, age, revealAge) {
  if (revealAge) {
    console.log(name + " is " + age + " years old.");
  } else {
    console.log(name + " does not want to reveal their age.");
  }
}
```

## 순차적 조건부 검사 방지

특히 긴 경우 `if...else` 체인을 읽기 어려울 수 있습니다.

### 예제 시나리오

이 Python 코드는 다양한 동물이 만드는 소리(정의된 경우)를 출력하거나 동물 유형이 인식되지 않는 경우 “알 수 없는 동물”을 출력합니다. 그러나 `if...else` 문 체인 때문에 코드가 비효율적이고 번거로워집니다.

```python id=animal-sound
class Animal:
    def speak(self):
        pass

class Dog(Animal):
    def speak(self):
        return "Woof!"

class Cat(Animal):
    def speak(self):
        return "Meow!"

class Bird(Animal):
    def speak(self):
        return "Tweet!"

def animal_sound(animal_type):
    if animal_type == "dog":
        return Dog().speak()
    elif animal_type == "cat":
        return Cat().speak()
    elif animal_type == "bird":
        return Bird().speak()
    else:
        return "Unknown animal"

print(animal_sound("dog"))
print(animal_sound("cat"))
print(animal_sound("bird"))
print(animal_sound("fish"))
```

### 예시 프롬프트

```copilot copy prompt ref=animal-sound
Simplify this code. Avoid using if/else chains but retain all function return values.
```

### 예제 응답

Copilot는 사전을 사용하여 동물 유형을 해당 클래스에 매핑할 것을 제안합니다.

```python
class Animal:
    def speak(self):
        pass

class Dog(Animal):
    def speak(self):
        return "Woof!"

class Cat(Animal):
    def speak(self):
        return "Meow!"

class Bird(Animal):
    def speak(self):
        return "Tweet!"

def animal_sound(animal_type):
    animals = {
        "dog": Dog,
        "cat": Cat,
        "bird": Bird
    }
    animal_class = animals.get(animal_type, Animal)
    return animal_class().speak() if animal_class != Animal else "Unknown animal"

print(animal_sound("dog"))
print(animal_sound("cat"))
print(animal_sound("bird"))
print(animal_sound("fish"))
```

## 중첩된 논리 감소

깊이 중첩된 구조는 코드를 따라가기 어렵게 만들 수 있으므로 나중에 코드의 논리를 수정하거나 확장하기가 어려울 수 있습니다.

### 예제 시나리오

이 Ruby 코드는 세 가지 매개 변수를 기반으로 사용자 계정에 대한 정보를 출력합니다. 중첩된 `if...else` 문을 사용하면 코드가 불필요하게 복잡해집니다.

```ruby id=determine-access
def determine_access(user_role, has_permission, is_active)
  if user_role == "admin"
    if has_permission
      if is_active
        "Active admin account with full access."
      else
        "Inactive admin account."
      end
    else
      "Admin account lacks necessary permissions."
    end
  else
    "Access denied."
  end
end

puts determine_access("admin", true, true)
puts determine_access("admin", true, false)
puts determine_access("admin", false, true)
puts determine_access("user", true, true)
```

### 예시 프롬프트

```copilot copy prompt ref=determine-access
Rewrite this code to avoid the nested if/else statements
```

### 예제 응답

Copilot는 가드 절을 사용하여 조건을 조기에 처리하고 적절한 메시지를 반환할 것을 제안합니다.

```ruby
def determine_access(user_role, has_permission, is_active)
  return "Access denied." unless user_role == "admin"
  return "Admin account lacks necessary permissions." unless has_permission
  return "Inactive admin account." unless is_active

  "Active admin account with full access."
end

puts determine_access("admin", true, true)
puts determine_access("admin", true, false)
puts determine_access("admin", false, true)
puts determine_access("user", true, true)
```

## 큰 메서드 분할

메서드나 함수가 너무 길면 정확히 파악하기 어려서 유지 관리가 어려울 수 있습니다. 여러 작업을 수행하는 메서드나 함수를 다른 컨텍스트에서 다시 사용할 수 없습니다. 격리된 각 작업을 테스트하는 것도 어려울 수 있습니다.

### 예제 시나리오

이 Java 메서드는 고객 주문을 처리하고 메시지를 출력합니다. 단일 메서드로 여러 작업을 수행합니다.

```java id=process-order
public void processOrder(Order order) {
  if (order == null || order.getItems().isEmpty()) {
    throw new IllegalArgumentException("Order is invalid.");
  }

  double totalPrice = 0.0;
  for (Item item : order.getItems()) {
    totalPrice += item.getPrice() * item.getQuantity();
  }
  order.setTotalPrice(totalPrice);

  if (totalPrice > 0) {
    order.setStatus("Processed");
  } else {
    order.setStatus("Pending");
  }

  System.out.println("Order for customer " + order.getCustomerName() + " has been processed. Total price: " + totalPrice);
}
```

### 예시 프롬프트

```copilot copy prompt ref=process-order
How could the processOrder method be refactored to be more useful and easier to maintain
```

### 예제 응답

Copilot는 이 메서드를 더 작고 집중적인 메서드로 나누는 것을 제안합니다.

```java
public void processOrder(Order order) {
    validateOrder(order);
    double totalPrice = calculateTotalPrice(order);
    updateOrderStatus(order, totalPrice);
    printOrderSummary(order, totalPrice);
}

private void validateOrder(Order order) {
    if (order == null || order.getItems().isEmpty()) {
        throw new IllegalArgumentException("Order is invalid.");
    }
}

private double calculateTotalPrice(Order order) {
    double totalPrice = 0.0;
    for (Item item : order.getItems()) {
        totalPrice += item.getPrice() * item.getQuantity();
    }
    order.setTotalPrice(totalPrice);
    return totalPrice;
}

private void updateOrderStatus(Order order, double totalPrice) {
    if (totalPrice > 0) {
        order.setStatus("Processed");
    } else {
        order.setStatus("Pending");
    }
}

private void printOrderSummary(Order order, double totalPrice) {
    System.out.println("Order for customer " + order.getCustomerName() + " has been processed. Total price: " + totalPrice);
}
```

## 추가 참고 자료

* [GitHub Copilot 채팅에 대한 프롬프트 엔지니어링](/ko/copilot/using-github-copilot/prompt-engineering-for-github-copilot)
* [GitHub 부필로트 사용에 대한 모범 사례](/ko/copilot/using-github-copilot/best-practices-for-using-github-copilot)