Early Returns
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)
{
// Return early if username is null
if (username == null)
return false;
// Return early if username is too short
if (username.Length < 3)
return false;
// Return early if username is too long
if (username.Length > 20)
return false;
// If we get here, username is valid
return true;
}조기 반환은 코드를 더 읽기 쉽게 만들고 들여쓰기 수준을 줄입니다.
챌린지
쉬움ProcessPayment라는 메서드를 작성하세요. 이 메서드는 다음에 기반하여 지불이 처리될 수 있는지 결정합니다:
- 지불 금액은 양수여야 합니다
- 계좌 잔액은 충분해야 합니다
- 계좌는 잠겨 있지 않아야 합니다
각 조건을 확인하고 적절한 오류 메시지를 반환하기 위해 조기 반환(early returns)을 사용하세요.
메서드는 다음을 수행해야 합니다:
- 세 개의 매개변수를 받습니다:
decimal paymentAmount,decimal accountBalance, 그리고bool isAccountLocked - "Payment processed successfully" 또는 오류 메시지 중 하나의 문자열을 반환합니다
- 유효성 검사를 위해 조기 반환을 사용합니다
오류 메시지를 정확히 다음 형식으로 출력하세요:
- "Error: Payment amount must be positive"
- "Error: Insufficient funds"
- "Error: Account is locked"
치트 시트
조기 반환은 조건이 충족되면 메서드를 즉시 종료하여 중첩 조건문을 피하고 들여쓰기를 줄입니다.
조기 반환 없이 (중첩 조건문):
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;
}조기 반환은 코드를 더 읽기 쉽게 만들고 들여쓰기 수준을 줄입니다.
직접 해보기
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);
}
}이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.
논리 및 흐름의 모든 레슨
1Multi-dimensional Arrays
2D Arrays BasicsDeclaring and Initializing 2DAccessing 2D Array ElementsNested Loops with 2D ArraysJagged ArraysCommon Matrix OperationsRecap - Multi-dimensional4Flow Control Techniques
Early ReturnsGuard ClausesJump Statements (goto)Break and ContinueFlatten Nested Conditionals7Logical Operators Advanced
Short-Circuit EvaluationConditional Logical OperatorsOperator PrecedenceRecap - Advanced Operators2Advanced Decision Making
Multiple ConditionsComplex Boolean LogicIf vs. Switch ComparisonNested Switch StatementsRecap - Advanced Decisions5Exception Handling
Try-Catch BasicsException TypesMultiple Catch BlocksWorking with FilesFinally BlockUsing vs. Try-FinallyCustom ExceptionsRecap - Error Handling3Loop Enhancements
Loop PerformanceIterating ComplexEach Loop TypeRefactoring LoopsRecap - Optimized Loops6Null Handling
Null Reference BasicsNullable Value TypesNull Checking PatternsDefensive ProgrammingRecap - Null Safety