연습 - 재사용 가능한 메서드 만들기
- 10분
애플리케이션을 개발할 때 동일한 작업을 반복해서 수행하는 코드를 작성할 수 있습니다. 중복 코드를 작성하는 대신 메서드를 사용하여 동일한 작업을 수행하면 코드가 단축되고 애플리케이션을 더 빠르게 개발할 수 있습니다. 이 연습에서는 반복되는 코드를 식별하고 재사용 가능한 메서드로 대체합니다. 시작해 봅시다!
중복된 코드 식별
이 작업에서는 여러 표준 시간대에서 약물 치료 시간을 추적하는 애플리케이션을 살펴보겠습니다. 사용자가 현재 표준 시간대 및 대상 표준 시간대를 입력합니다. 그들의 약물 일정이 표시되고 새로운 시간대에 맞춰 조정된다.
Visual Studio Code 편집기에서 이전 연습의 기존 코드를 모두 삭제합니다.
다음 코드를 복사하여 Visual Studio Code 편집기에 붙여넣습니다.
using System; int[] times = {800, 1200, 1600, 2000}; int diff = 0; Console.WriteLine("Enter current GMT"); int currentGMT = Convert.ToInt32(Console.ReadLine()); Console.WriteLine("Current Medicine Schedule:"); /* Format and display medicine times */ foreach (int val in times) { string time = val.ToString(); int len = time.Length; if (len >= 3) { time = time.Insert(len - 2, ":"); } else if (len == 2) { time = time.Insert(0, "0:"); } else { time = time.Insert(0, "0:0"); } Console.Write($"{time} "); } Console.WriteLine(); Console.WriteLine("Enter new GMT"); int newGMT = Convert.ToInt32(Console.ReadLine()); if (Math.Abs(newGMT) > 12 || Math.Abs(currentGMT) > 12) { Console.WriteLine("Invalid GMT"); } else if (newGMT <= 0 && currentGMT <= 0 || newGMT >= 0 && currentGMT >= 0) { diff = 100 * (Math.Abs(newGMT) - Math.Abs(currentGMT)); /* Adjust the times by adding the difference, keeping the value within 24 hours */ for (int i = 0; i < times.Length; i++) { times[i] = ((times[i] + diff)) % 2400; } } else { diff = 100 * (Math.Abs(newGMT) + Math.Abs(currentGMT)); /* Adjust the times by adding the difference, keeping the value within 24 hours */ for (int i = 0; i < times.Length; i++) { times[i] = ((times[i] + diff)) % 2400; } } Console.WriteLine("New Medicine Schedule:"); /* Format and display medicine times */ foreach (int val in times) { string time = val.ToString(); int len = time.Length; if (len >= 3) { time = time.Insert(len - 2, ":"); } else if (len == 2) { time = time.Insert(0, "0:"); } else { time = time.Insert(0, "0:0"); } Console.Write($"{time} "); } Console.WriteLine();동일한 코드로 반복되는 여러
for-loop가 있습니다.약 시간을 포맷하고 표시하는 두 개의
foreach루프가 있습니다. 표준 시간대 차이에 따라 시간을 조정하는 또 다른 두for개의 루프가 있습니다.코드를 작성할 때 동일한 작업을 수행하기 위해 코드 블록을 반복할 수 있습니다. 메서드를 사용함으로써 해당 작업을 수행하여 코드를 정리할 수 있는 완벽한 기회입니다. 연습해 봅시다!
반복되는 작업을 수행하는 메서드 만들기
이제 반복되는 코드를 확인했으므로 코드를 포함하는 메서드를 만들고 중복 항목을 제거할 수 있습니다. 메서드를 사용하면 코드를 단축하고 가독성을 향상시킬 수 있습니다. 루프는 foreach 시간 값의 형식을 지정하고 표시하므로 메서드에 해당 작업을 명확하게 반영하는 이름을 지정할 수 있습니다. 시간을 조정하는 루프를 for 사용하여 동일한 작업을 수행할 수 있습니다. 시작해 봅시다!
이전 코드의 끝에 새 빈 코드 줄을 입력합니다.
새 빈 코드 줄에서 다음 코드를 입력하여 메서드 서명을 만듭니다.
void DisplayTimes() { }메서드 본문을 정의하려면
DisplayTimes메서드를 업데이트하고foreach블록을 다음과 같이 복사하고 붙여넣습니다.void DisplayTimes() { /* Format and display medicine times */ foreach (int val in times) { string time = val.ToString(); int len = time.Length; if (len >= 3) { time = time.Insert(len - 2, ":"); } else if (len == 2) { time = time.Insert(0, "0:"); } else { time = time.Insert(0, "0:0"); } Console.Write($"{time} "); } Console.WriteLine(); }이 메서드에서는 시간이 표시된 후 새 줄을 추가하기 위해 끝에 호출
Console.WriteLine을 포함합니다. 다음으로 표준 시간대 차이에 따라 시간을 조정하는 다른 메서드를 만듭니다.이전 코드의 끝에 새 빈 코드 줄을 입력합니다.
새 빈 코드 줄에서 다음 코드를 입력하여 메서드 서명을 만듭니다.
void AdjustTimes() { }AdjustTimes다음과 같이 루프를 복사하고 붙여넣어for메서드를 업데이트합니다.void AdjustTimes() { /* Adjust the times by adding the difference, keeping the value within 24 hours */ for (int i = 0; i < times.Length; i++) { times[i] = ((times[i] + diff)) % 2400; } }
3단계: 메서드 호출
이 작업에서는 반복된 코드 블록을 삭제하고 사용자가 만든 메서드에 대한 호출로 대체합니다.
"약 시간 서식 지정 및 표시"라는 주석 아래에서 반복되는
foreach루프의 첫 번째 인스턴스를 찾습니다.Console.WriteLine("Current Medicine Schedule:"); /* Format and display medicine times */ foreach (int val in times) { ... } Console.WriteLine(); Console.WriteLine("Enter new GMT");식별한 코드를 메서드 호출
DisplayTimes로 바꿉다. 대체하면 다음 코드가 생성됩니다.Console.WriteLine("Current Medicine Schedule:"); DisplayTimes(); Console.WriteLine("Enter new GMT");다음으로 반복 코드의 두 번째 인스턴스를 바꿉 있습니다.
"의학 시간 서식 지정 및 표시"라는 주석 아래에서 루프의
foreach두 번째 인스턴스를 찾습니다.Console.WriteLine("New Medicine Schedule:"); /* Format and display medicine times */ foreach (int val in times) { ... } Console.WriteLine();식별한 코드를 메서드 호출
DisplayTimes로 바꿉다. 대체하면 다음 코드가 생성됩니다.Console.WriteLine("New Medicine Schedule:"); DisplayTimes();큰 코드 블록 대신 메서드를 사용하면 더 명확하게 표시되고 코드를 더 쉽게 이해할 수 있습니다. 만든 메서드를
AdjustTimes사용하여 동일한 작업을 수행해 보겠습니다.중복된
for-loops를 사용하여 다음 코드를 찾습니다.else if (newGMT <= 0 && currentGMT <= 0 || newGMT >= 0 && currentGMT >= 0) { diff = 100 * (Math.Abs(newGMT) - Math.Abs(currentGMT)); /* Adjust the times by adding the difference, keeping the value within 24 hours */ for (int i = 0; i < times.Length; i++) { times[i] = ((times[i] + diff)) % 2400; } } else { diff = 100 * (Math.Abs(newGMT) + Math.Abs(currentGMT)); /* Adjust the times by adding the difference, keeping the value within 24 hours */ for (int i = 0; i < times.Length; i++) { times[i] = ((times[i] + diff)) % 2400; } }"‘차이를 추가하여 시간 조정’이라는 주석 아래의 반복되는 코드 인스턴스를
AdjustTimes메서드 호출로 바꾸세요." 대체하면 다음 코드가 생성됩니다.else if (newGMT <= 0 && currentGMT <= 0 || newGMT >= 0 && currentGMT >= 0) { diff = 100 * (Math.Abs(newGMT) - Math.Abs(currentGMT)); AdjustTimes(); } else { diff = 100 * (Math.Abs(newGMT) + Math.Abs(currentGMT)); AdjustTimes(); }이제 중복된 모든 코드가 새 메서드로 대체되었습니다. 코드가 얼마나 쉽게 읽을 수 있고 간결하게 표시되는지 확인합니다.
작업 결과 확인
이 작업에서는 통합 터미널에서 애플리케이션을 실행하고 코드가 올바르게 작동하는지 확인합니다. 시작해 보겠습니다.
코드를 다음과 비교하여 올바른지 확인합니다.
int[] times = {800, 1200, 1600, 2000}; int diff = 0; Console.WriteLine("Enter current GMT"); int currentGMT = Convert.ToInt32(Console.ReadLine()); Console.WriteLine("Current Medicine Schedule:"); DisplayTimes(); Console.WriteLine("Enter new GMT"); int newGMT = Convert.ToInt32(Console.ReadLine()); if (Math.Abs(newGMT) > 12 || Math.Abs(currentGMT) > 12) { Console.WriteLine("Invalid GMT"); } else if (newGMT <= 0 && currentGMT <= 0 || newGMT >= 0 && currentGMT >= 0) { diff = 100 * (Math.Abs(newGMT) - Math.Abs(currentGMT)); AdjustTimes(); } else { diff = 100 * (Math.Abs(newGMT) + Math.Abs(currentGMT)); AdjustTimes(); } Console.WriteLine("New Medicine Schedule:"); DisplayTimes(); void DisplayTimes() { /* Format and display medicine times */ foreach (int val in times) { string time = val.ToString(); int len = time.Length; if (len >= 3) { time = time.Insert(len - 2, ":"); } else if (len == 2) { time = time.Insert(0, "0:"); } else { time = time.Insert(0, "0:0"); } Console.Write($"{time} "); } Console.WriteLine(); } void AdjustTimes() { /* Adjust the times by adding the difference, keeping the value within 24 hours */ for (int i = 0; i < times.Length; i++) { times[i] = ((times[i] + diff)) % 2400; } }Ctrl + S를 사용하거나 Visual Studio Code 파일 메뉴를 사용하여 작업을 저장합니다.
필요한 경우 Visual Studio Code의 통합 터미널 패널을 엽니다.
탐색기 패널에서 TestProject 폴더 위치에서 터미널을 열려면 TestProject를 마우스 오른쪽 단추로 클릭한 다음 통합 터미널에서 열기를 선택합니다.
터미널 명령 프롬프트에서 dotnet run을 입력합니다.
GMT 프롬프트에 대해 -6 및 +6을 입력합니다.
코드가 다음 출력을 생성하는지 확인합니다.
Enter current GMT -6 Current Medicine Schedule: 8:00 12:00 16:00 20:00 Enter new GMT +6 New Medicine Schedule: 20:00 0:00 4:00 8:00코드가 다른 결과를 표시하는 경우 코드를 검토하여 오류를 찾고 업데이트해야 합니다. 코드를 다시 실행하여 문제가 해결되었는지 확인합니다. 코드가 예상 결과를 생성할 때까지 코드를 계속 업데이트하고 실행합니다.