Early Returns
Part of the Logic & Flow section of Coddy's C# journey — lesson 18 of 66.
Early returns are a technique where we exit a method as soon as we have the answer or encounter an invalid condition, rather than nesting conditionals.
Let's compare two approaches to validate a username:
Without early returns (nested conditionals):
public bool ValidateUsername(string username)
{
bool isValid = false;
if (username != null)
{
if (username.Length >= 3)
{
if (username.Length <= 20)
{
isValid = true;
}
}
}
return isValid;
}With early returns:
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;
}Early returns make code more readable and reduce indentation levels.
Challenge
EasyWrite a method called ProcessPayment that determines if a payment can be processed based on:
- The payment amount must be positive
- The account balance must be sufficient
- The account must not be locked
Use early returns to check each condition and return appropriate error messages.
The method should:
- Take three parameters:
decimal paymentAmount,decimal accountBalance, andbool isAccountLocked - Return a string with either "Payment processed successfully" or an error message
- Use early returns for validation
Print error messages in exactly these formats:
- "Error: Payment amount must be positive"
- "Error: Insufficient funds"
- "Error: Account is locked"
Cheat sheet
Early returns exit a method immediately when a condition is met, avoiding nested conditionals and reducing indentation.
Without early returns (nested conditionals):
public bool ValidateUsername(string username)
{
bool isValid = false;
if (username != null)
{
if (username.Length >= 3)
{
if (username.Length <= 20)
{
isValid = true;
}
}
}
return isValid;
}With early returns:
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;
}Early returns make code more readable and reduce indentation levels.
Try it yourself
using System;
public class Program
{
public static string ProcessPayment(decimal paymentAmount, decimal accountBalance, bool isAccountLocked)
{
// Write your code here
}
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);
}
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
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