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

Enums - An introduction

Enums - An introduction

Tommy Mühle

August 24, 2017
Tweet

More Decks by Tommy Mühle

Other Decks in Programming

Transcript

  1. Tommy Mühle | tommy-muehle.io Tommy Mühle | tommy-muehle.io … a

    data type consisting of a set of named values called elements … of the type. 
 The enumerator names are usually identifiers that behave as constants in the language. https:/ /en.wikipedia.org/wiki/Enumerated_type
  2. Tommy Mühle | tommy-muehle.io 10 Avoid global constants // app.php

    const STATE_ACTIVE = 'active'; const STATE_COMPLETED = 'completed'; $app = new Application(); $app->setState(STATE_ACTIVE); // ... return $app->run();
  3. Tommy Mühle | tommy-muehle.io 11 class StateHandler { const STATE_ACTIVE

    = 'active'; const STATE_CANCELED = 'canceled'; public function handle($state) { if ($state !== self::STATE_ACTIVE) { // ... } // ... } } Avoid class constants
  4. Tommy Mühle | tommy-muehle.io 13 final class Color { const

    __DEFAULT = 'black'; const RED = 'red'; private $value; public function __construct(string $color = null) { $this->value = $color ?? self::__DEFAULT; } public function __toString() { return $this->value; } }
  5. Tommy Mühle | tommy-muehle.io 16 final class Color { //

    ... public function __construct(string $color = null) { $value = $color ?? self::__DEFAULT; if (!in_array($value, $this->all(), true)) { // ... } $this->value = $value; } public function all() : array { return (new \ReflectionClass(static::class))
 ->getConstants(); } // ... }
  6. Tommy Mühle | tommy-muehle.io 18 class Article { private $color;

    public function colorize(Color $color) { // ... } }
  7. Tommy Mühle | tommy-muehle.io 20 final class Color { //

    ... protected $value; // ... public function value() { return $this->value; } public function equals(Color $color) { // or any other business condition return $this->value === $color->value(); } }
  8. Tommy Mühle | tommy-muehle.io 21 final class Color { //

    ... protected $value; // ... public static function fromHex(string $hex) { // do something with $hex and get $color return new self($color); } public function format() { return 'My special color format'; } }
  9. Tommy Mühle | tommy-muehle.io 23 // if class Color are

    not final final class SpecialColor extends Color { // add further values, enrich methods, etc. }