Menu
CoddyTech

조기 반환

Coddy C# 여정의 논리 및 흐름 섹션에 포함된 레슨. 66개 중 18번째.

조기 반환은 조건문을 중첩하는 대신, 답을 얻거나 유효하지 않은 조건을 만나면 즉시 메서드를 종료하는 기법입니다.

사용자 이름을 검증하는 두 가지 접근 방식을 비교해 보겠습니다.

조기 반환을 사용하지 않는 경우(중첩 조건문):

public bool ValidateUsername(string username)
{
    bool isValid = false;
    
    if (username != null)
    {
        if (username.Length >= 3)
        {
            if (username.Length <= 20)
            {
                isValid = true;
            }
        }
    }
    
    return isValid;
}

조기 반환 사용:

public bool ValidateUsername(string username)
{
    // username이 null이면 즉시 반환합니다
    if (username == null)
        return false;
        
    // username이 너무 짧으면 즉시 반환합니다
    if (username.Length < 3)
        return false;
        
    // username이 너무 길면 즉시 반환합니다
    if (username.Length > 20)
        return false;
        
    // 여기까지 왔다면 username은 유효합니다
    return true;
}

조기 반환은 코드를 더 읽기 쉽게 만들고 들여쓰기 단계를 줄여 줍니다.

challenge icon

챌린지

쉬움

결제 처리 가능 여부를 다음 조건에 따라 판단하는 ProcessPayment 메서드를 작성하세요.

  1. 결제 금액은 양수여야 합니다
  2. 계정 잔액은 충분해야 합니다
  3. 계정이 잠겨 있지 않아야 합니다

각 조건을 확인하고 적절한 오류 메시지를 반환하도록 조기 반환을 사용하세요.

메서드는 다음을 수행해야 합니다.

  • 매개변수 세 개를 받습니다: decimal paymentAmount, decimal accountBalance, bool isAccountLocked
  • "Payment processed successfully" 또는 오류 메시지가 담긴 문자열을 반환합니다
  • 유효성 검사에 조기 반환을 사용합니다

오류 메시지를 다음 형식과 정확히 일치하게 출력하세요.

  • "Error: Payment amount must be positive"
  • "Error: Insufficient funds"
  • "Error: Account is locked"

직접 해보기

using System;

public class Program
{
    public static string ProcessPayment(decimal paymentAmount, decimal accountBalance, bool isAccountLocked)
    {
        // 여기에 코드를 작성하세요
    }
    
    public static void Main(string[] args)
    {
        decimal paymentAmount = decimal.Parse(Console.ReadLine());
        decimal accountBalance = decimal.Parse(Console.ReadLine());
        bool isAccountLocked = bool.Parse(Console.ReadLine());
        
        string result = ProcessPayment(paymentAmount, accountBalance, isAccountLocked);
        Console.WriteLine(result);
    }
}
quiz icon실력 점검

이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.

논리 및 흐름의 모든 레슨

직접 연습해 보세요: 온라인 C# 컴파일러