Guard & validation patterns
Validate inputs early with guard clauses, throw the right exceptions, and use TryParse-style checks for user data.
Why guards
Aim: Keep methods safe and readable.
- Use guard clauses at the top
- Throw specific exceptions (ArgumentNullException, ArgumentOutOfRangeException)
- Use TryParse for user input
- Fail fast; avoid deep nesting
Early guards demo
Add small checks at the top to validate arguments; throw specific exceptions so callers know what went wrong.
using System;
// Demo: validate inputs at the top; keep main logic flat.
public class Program
{
// Compute price with simple rules; guard early.
public static decimal ComputePrice(string sku, int qty, decimal unitPrice)
{
if (sku == null) throw new ArgumentNullException("sku");
if (sku.Length == 0) throw new ArgumentException("sku must not be empty", "sku");
if (qty <= 0) throw new ArgumentOutOfRangeException("qty", "qty must be > 0");
if (unitPrice < 0m) throw new ArgumentOutOfRangeException("unitPrice", "unitPrice must be >= 0");
// Main logic stays simple
decimal subtotal = qty * unitPrice;
if (qty >= 10) subtotal = subtotal * 0.9m; // small bulk discount
return subtotal;
}
public static void Main(string[] args)
{
Console.WriteLine(ComputePrice("ABC", 2, 5m)); // ok
try { Console.WriteLine(ComputePrice("", 2, 5m)); } catch (Exception ex) { Console.WriteLine(ex.GetType().Name); }
}
}
All lessons in this course
- Logging abstractions, Debug/Trace
- Basic profiling & traces (concepts)
- Guard & validation patterns