Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Why setters are bad

Why setters are bad

Inspired by "Implementing DDD" some examples why setters are bad and how you can avoid these - Internal tech-talk at move:elevator

Tommy Mühle

May 02, 2017
Tweet

More Decks by Tommy Mühle

Other Decks in Programming

Transcript

  1. Tommy Mühle | tommy-muehle.io 6 class Article { private $state

    = 'unknown'; // ... public function setState($state) { if ($state === 'unknown') { // ... } $this->state = $state; } }
  2. Tommy Mühle | tommy-muehle.io 8 class Article { private $state

    = 'unknown'; // ... public function publish() { $this->state = 'published'; } }
  3. Tommy Mühle | tommy-muehle.io 13 class Article { private $title;

    private $state; // ... public static function draft($title) { $article = new self(); $article->state = 'draft'; $article->title = $title; return $article; } }
  4. Tommy Mühle | tommy-muehle.io 15 class Article { private $deleted

    = false; // ... public function setDeleted($deleted) { $this->deleted = (bool) $deleted; } // ... } Boolean flag parameters
  5. Tommy Mühle | tommy-muehle.io 16 Avoid boolean parameters class Article

    { private $deleted = false; // ... public function delete() { $this->deleted = true; } // ... }
  6. Tommy Mühle | tommy-muehle.io 18 Avoid setter injection class MyService

    { private $logger; // ... public function setLogger($logger) { $this->logger = $logger; } }
  7. Tommy Mühle | tommy-muehle.io 19 Avoid unnecessary conditions class MyService

    { private $logger; // ... public function myMethod(array $parameters) { // ... if ($this->logger instanceof LoggerInterface) { $this->logger->log('...'); } } }
  8. Tommy Mühle | tommy-muehle.io 21 class MyService { private $logger;

    // ... public function __construct($logger) { $this->logger = $logger; } } Make immutable objects