Roadmap › Clean Code, Testing & Best Practices › Module: Readable Code
Lessons in this course (12)
2. Functions, parameters and guard clauses
Basic★ Must knowLesson 2 of 12
- Small; do one thing; one level of abstraction.
- Few parameters (≤ 3); group many into a parameter object/record.
- No hidden side effects; avoid boolean "flag" parameters that switch behaviour.
- Return early with guard clauses instead of deep nesting.
csharp
// ❌ Arrow code
public decimal Ship(Order o)
{
if (o != null) { if (o.IsPaid) { if (o.Lines.Count > 0) { return Calculate(o); } else throw ...; } else throw ...; }
else throw ...;
}
// ✅ Guard clauses
public decimal Ship(Order? o)
{
ArgumentNullException.ThrowIfNull(o);
if (!o.IsPaid) throw new InvalidOperationException("Order not paid");
if (o.Lines.Count == 0) throw new InvalidOperationException("Order is empty");
return Calculate(o);
}