DEV Community

[Comment from a deleted post]
Collapse
 
phpandcigars profile image
PHP and cigars • Edited

You say defensive programming is not about clean code. I would strongly disagree with you. Let's take your example.

<?php

$message = new Message();
$message->setContent("bob message");
$joeMailer = new Mailer($message);

$message->setContent("joe message");
$bobMailer = new Mailer($message);

$joeMailer->sendMessage();
$bobMailer->sendMessage();

This is clearly an issue of clean code. The error happens, because this is not in a function. And for functions there is a rule. A function does one thing, and one thing only.

PHP7 added anonymous classes for the purpose to use them in little plain scripts like these.
Let's take a look at the following example of how the error could be avoided:

<?php

$c = new Class {

    public function __construct() {
        $this->sendBobMessage();
        $this->sendJoeMessage();
    }

    private function sendBobMessage() {
        $m = new Message();
        $m->setContent("bob message");
        $mailer = new Mailer($m);
        $mailer->sendMessage();
    }

    private function sendJoeMessage() {
        $m = new Message();
        $m->setContent("joe message");
        $mailer = new Mailer($m);
        $mailer->sendMessage();
    }

};

Of course, the methods sendBobMessage() and sendJoeMessage() still do not comply with the rule that a function should do one thing only, but this improvement is enough to avoid your bug.

In your example you can pass all arguments to the Message class. But Imagine, you would have more arguments (like from, to, subject, html_message). I don't like the approach to pass all arguments to a constructor, specially when arguments are optional.

I hope, this is not to rude.