Behave!

In favour of behaviours in OOP

Urban Etter

OOP in school


class Animal { ... }

class Cat extends Animal { ... }
					

$kitten = new Cat();
					

$kitten

is of type

Cat

Let the animals jump!

4 legs

2 legs

Types of classes

  • Representers
  • Doers
  • Plumbers
  • Translators
  • Makers

'type of'

only really works

for representers

What if there is a

better way

to look at OOP?

Behaviours

Specification vs Implementation

What vs How

Specification or Implementation

  • Interface: Specification
  • Trait: Implementation
  • Class: Specification and Implementation

// Represents a cat
class Cat {
  public $name;
}
					

// Specification of behaviour 'jump'
interface CanJump {
  public function jump();
}
					

// Implementation of behaviour 'jump'
class FourLeggedJumper implements CanJump {
  public function jump() {
    ...
  }
}
					

class Cat implements CanJump {
  // @var CanJump
  private $jumper;

  public function jump() {
    $this->jumper->jump();
  } 
}
					

$runner = new FourLeggedJumper();
$kitten = new Cat();
$kitten->setJumper($jumper);
$kitten->jump();
					

$fourLegs = new FourLeggedJumper();
$twoLegs = new TwoLeggedJumper();

$kitten = new Cat($fourLegs);
$doggie = new Dog($fourLegs);
$ralf = new Human($twoLegs);

if ($forrest instanceof CanJump)
   $forrest->jump();
					

Impacts

  • More entities (more complex for easiest use case, way better for real life)
  • Seperation between specification and implementation
  • Mix and match behaviours
  • Better readability and maintainability

Don't think about

Type

Think about

Behaviours

Thanks!

Credits: @ircmaxell