Menu
Coddy logo textTech

Early Returns

CoddyのC#ジャーニー「ロジックとフロー」セクションの一部 — レッスン 18/66。

早期リターンは、答えが得られた時点や無効な条件に遭遇した時点でメソッドをすぐに終了するテクニックで、条件分岐をネストさせるのではなく用いられます。

ユーザー名を検証するための2つのアプローチを比較してみましょう:

早期リターンなし(ネストされた条件分岐):

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. 口座がロックされていない必要があります

各条件をチェックするために early return を使用し、適切なエラーメッセージを返してください。

メソッドは以下の仕様に従います:

  • 3つのパラメータを受け取る:decimal paymentAmountdecimal accountBalance、および bool isAccountLocked
  • "Payment processed successfully" またはエラーメッセージのいずれかの文字列を返す
  • 検証のために early return を使用する

エラーメッセージを以下の正確な形式で出力してください:

  • "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)
{
    // 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;
}

早期リターンはコードをより読みやすくし、インデントレベルを減らします。

自分で試してみよう

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腕試し

このレッスンには短いクイズがあります。レッスンを始めて解答し、進捗を記録しましょう。

ロジックとフローのすべてのレッスン