Menu
Coddy logo textTech

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 icon

Challenge

Easy

Create a method named ProcessUserData that accepts a string parameter userData. The method should:

  1. Check if userData is null - if it is, print "Error: User data is null" and return.
  2. Check if userData is empty - if it is, print "Error: User data is empty" and return.
  3. 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
    }
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Logic & Flow