The Art of Defensive Programming

Diego
Diego
Dec 25, 2016 · 6 min read

A first sight to Defensive Programming

Never trust user input

The best defense is a good offense

Use database abstraction

Don’t reinvent the wheel

Don’t trust developers

Write SOLID code

<?phpclass BankAccount
{
protected $currency = null;
public function setCurrency($currency) { ... }
public function payTo(Account $to, $amount)
{
// sorry for this silly example
$this->transaction->process($to, $amount, $this->currency);
}
}
// I forgot to call $bankAccount->setCurrency('GBP');
$bankAccount->payTo($joe, 100);
<?phpclass BankAccount
{
public function payTo(Account $to, Money $money) { ... }
}
$bankAccount->payTo($joe, new Money(100, new Currency('GBP')));
<?phpclass Message
{
protected $content;
public function setContent($content)
{
$this->content = $content;
}
}
class Mailer
{
protected $message;
public function __construct(Message $message)
{
$this->message = $message;
}
public function sendMessage(){
var_dump($this->message);
}
}
$message = new Message();
$message->setContent("bob message");
$joeMailer = new Mailer($message);
$message->setContent("joe message");
$bobMailer = new Mailer($message);
$joeMailer->sendMessage();
$bobMailer->sendMessage();
<?phpclass Message
{
protected $content;
public function __construct($content)
{
$this->content = $content;
}
}
class Mailer
{
protected $message;
public function __construct(Message $message)
{
$this->message = $message;
}
public function sendMessage(
{
var_dump($this->message);
}
}
$joeMailer = new Mailer(new Message("bob message"));
$bobMailer = new Mailer(new Message("joe message"));
$joeMailer->sendMessage();
$bobMailer->sendMessage();

Write tests

Conclusions


WengVox

WengVox is a blog series about software engineering

Diego

Written by

Diego

http://diego.pizza

WengVox

WengVox

WengVox is a blog series about software engineering