thakurcoder

March 23, 2025

· 6 min read

A Fun Adventure into Defensive Programming

Discover how defensive programming makes your code strong and reliable, explained in a fun way with PHP and Laravel examples—like building a superhero robot that never breaks!

Hey there, coders! Imagine you're building a super cool toy robot that can run around and solve puzzles—like a mini version of those coding websites where you test your skills. Today, we’re going to learn about something called defensive programming. It’s like giving your robot a shield and a helmet so it doesn’t trip over toys, crash into walls, or break down when someone gives it silly instructions. Let’s dive in with a fun story and some examples using PHP and Laravel—languages you might use to build awesome websites!


What’s Defensive Programming Anyway?

Think of defensive programming as teaching your robot to be extra careful. It’s all about making sure your code doesn’t get confused or stop working, even if something unexpected happens. I learned this while building a project called ReelCode—a fun site where people write code to solve problems, kind of like a game. I wanted it to be super strong, so it wouldn’t crash, even if someone tried something tricky.

Let’s explore how I made it tough with some cool tricks—and I’ll show you how to do it with PHP and Laravel examples instead of my original Golang ones. Ready? Let’s go!


Trick #1: Checking Everything Before You Start (Input Validation)

Imagine your robot needs instructions—like “move forward” or “turn left.” But what if someone says, “fly to the moon”? Your robot doesn’t have wings! So, you check the instructions first to make sure they make sense.

In coding, this is called input validation. It’s like making sure the pieces fit before you build something. Here’s how it might look in Laravel:

// In a Laravel controller
public function submitCode(Request $request)
{
    // Check if all the important stuff is there
    $request->validate([
        'user_id' => 'required|exists:users,id', // Is this a real user?
        'source_code' => 'required|string',       // Did they send code?
        'language' => 'required|in:php,python',   // Is it a language we know?
        'problem_id' => 'required|exists:problems,id', // Is this a real problem?
    ]);
 
    // Yay! Everything looks good—let’s keep going!
    return "Code accepted!";
}

See? Laravel’s validate method is like a toy inspector. It says, “Nope, you can’t sneak in a blank piece or a made-up language!” This keeps your robot (or website) safe from bad instructions.


Trick #2: Catching Mistakes Like a Superhero (Error Handling)

Now, imagine your robot is carrying a big stack of blocks, but one slips and falls. If it just keeps walking, it might trip over the mess! Instead, you teach it to stop, pick up the block, and keep going—or at least tell you what went wrong.

In PHP, we use error handling to catch problems. Without it, your code might just crash and show a boring “Oops” page. Here’s a simple PHP example:

[[NEWSLETTER]]

try {
    // Pretend we're saving a file with the user's code
    $file = fopen('user_code.php', 'w');
    if ($file === false) {
        throw new Exception("Oh no! I couldn’t open the file!");
    }
    fwrite($file, "echo 'Hello, world!';");
    fclose($file);
} catch (Exception $e) {
    // Tell someone about the problem
    echo "Robot says: " . $e->getMessage();
    // Maybe log it so you can fix it later
}

In Laravel, it’s even easier because the framework catches most errors for you and shows a nice error page. But for super-important stuff, you can add your own safety net:

public function processCode()
{
    try {
        // Imagine this is a tricky step—like running the user’s code
        $result = SomeService::runCode();
    } catch (Exception $e) {
        // Oops! Let’s save the mistake and tell the user
        Log::error("Robot tripped: " . $e->getMessage());
        return response()->json(['error' => 'Something went wrong!'], 500);
    }
    return "All done!";
}

This way, your robot doesn’t fall apart—it just says, “Hey, I need help!”


Trick #3: Adding Clues to Mistakes (Wrapping Errors)

Sometimes, when your robot trips, it just says, “I fell!” That’s not very helpful. Was it a banana peel or a missing wheel? Wrapping errors is like giving it a little note that explains more.

Here’s a PHP example:

function saveCodeToFile($code)
{
    try {
        $file = fopen('code.php', 'w');
        if ($file === false) {
            throw new Exception("File wouldn’t open!");
        }
        fwrite($file, $code);
        fclose($file);
    } catch (Exception $e) {
        // Wrap the error with a bigger explanation
        throw new Exception("Couldn’t save the code to a file: " . $e->getMessage());
    }
}

Now, if something goes wrong, you’ll see, “Couldn’t save the code to a file: File wouldn’t open!” That’s way more helpful when you’re trying to fix it, right?

In Laravel, you might do this with a custom exception:

class CodeSaveException extends Exception {}
 
public function saveCode($code)
{
    try {
        // Try to save the code
        File::put('code.php', $code);
    } catch (Exception $e) {
        throw new CodeSaveException("Failed to save your code: " . $e->getMessage());
    }
}

It’s like putting a big, colorful sticky note on the problem!


Trick #4: Making Sure Everything’s Ready (Assertions)

Imagine your robot is about to race, but it doesn’t have batteries yet. You wouldn’t start the race, right? Assertions are like little checkpoints to make sure everything’s ready before you go.

In PHP, it’s just a simple “if” check:

function startRace($robot)
{
    if ($robot->hasBatteries() == false) {
        return "Wait! The robot needs batteries!";
    }
    // Okay, now we can race!
    return "Zoom! Off we go!";
}

In Laravel, maybe you’re checking if a user’s code is ready to run:

public function runCode($submission)
{
    if ($submission->status != 'code_executed') {
        return "Hold on! The code isn’t ready yet!";
    }
    if (empty($submission->output)) {
        return "Oops! There’s no output to check!";
    }
    // Now we can check if it’s correct
    return "Checking the code...";
}

These checks stop your robot from doing silly things—like racing without power or checking code that hasn’t even run yet!


Why It’s So Cool

Building ReelCode taught me that defensive programming is like giving your robot superpowers. It won’t crash if someone forgets a battery, drops a block, or gives it weird instructions. With tricks like validation, error handling, wrapping, and assertions, your code becomes tough and reliable—like a superhero toy!

So, next time you’re coding in PHP or Laravel, think of your program as a little robot. Add some shields with these tricks, and it’ll keep running smoothly, no matter what adventures come its way. Happy coding, little hero!