Defensive Programming
Part of the Logic & Flow section of Coddy's C# journey — lesson 34 of 66.
Defensive programming is a technique that helps prevent errors caused by null references. It involves checking for null values before attempting to use objects.
Check for null before using an object:
string name = GetNameFromSomewhere();
// Defensive check
if (name == null)
{
// Handle the null case
name = "Default Name";
}
// Now it's safe to use name
Console.WriteLine(name.ToUpper());Validate parameters in methods:
public void ProcessOrder(Order order)
{
// Defensive check for null parameter
if (order == null)
{
Console.WriteLine("Error: Order cannot be null");
return;
}
// Now safe to process the order
Console.WriteLine("Processing order: " + order.Id);
}Use conditional access operator (?.) for cleaner null checks:
Customer customer = GetCustomerFromSomewhere();
// Instead of:
// string city = null;
// if (customer != null && customer.Address != null)
// {
// city = customer.Address.City;
// }
// Use this:
string city = customer?.Address?.City;Challenge
EasyCreate a method named ProcessUserData that accepts a string parameter userData. The method should:
- Check if
userDatais null - if it is, print "Error: User data is null" and return. - Check if
userDatais empty - if it is, print "Error: User data is empty" and return. - If the data is valid, convert it to uppercase and print "Processing: [UPPERCASE_DATA]".
Cheat sheet
Defensive programming prevents errors by checking for null values before using objects.
Check for null before using an object:
string name = GetNameFromSomewhere();
if (name == null)
{
name = "Default Name";
}
Console.WriteLine(name.ToUpper());Validate parameters in methods:
public void ProcessOrder(Order order)
{
if (order == null)
{
Console.WriteLine("Error: Order cannot be null");
return;
}
Console.WriteLine("Processing order: " + order.Id);
}Use conditional access operator (?.) for cleaner null checks:
Customer customer = GetCustomerFromSomewhere();
string city = customer?.Address?.City;Try it yourself
using System;
class ProcessUserData
{
public static void processUserData(string userData)
{
// Hint: the string "null" should be treated as an actual null value
// Write your code here
}
}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