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;
}早期リターンはコードをより読みやすくし、インデントレベルを減らします。
チャレンジ
簡単ProcessPayment という名前のメソッドを書きなさい。このメソッドは、以下の条件に基づいて支払いが処理可能かどうかを判定します:
- 支払い金額は正である必要があります
- 口座残高が十分である必要があります
- 口座がロックされていない必要があります
各条件をチェックするために early return を使用し、適切なエラーメッセージを返してください。
メソッドは以下の仕様に従います:
- 3つのパラメータを受け取る:
decimal paymentAmount、decimal 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);
}
}このレッスンには短いクイズがあります。レッスンを始めて解答し、進捗を記録しましょう。
ロジックとフローのすべてのレッスン
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