Skip to content

Instantly share code, notes, and snippets.

@thekid
Last active August 29, 2015 14:13
Show Gist options
  • Select an option

  • Save thekid/03064f037d5b426404c2 to your computer and use it in GitHub Desktop.

Select an option

Save thekid/03064f037d5b426404c2 to your computer and use it in GitHub Desktop.
Brainstorming for sequence handling split based on element criteria
<?php
use util\data\Sequence;
class Types extends \lang\Enum {
public static $OPEN, $CLOSED;
}
class Wall extends \lang\Object {
private $name, $type;
public function __construct($name, Types $type) {
$this->name= $name;
$this->type= $type;
}
public function name() { return $this->name; }
public function type() { return $this->type; }
}
class Test extends \lang\Object {
static function __static() { Types::__static(); }
public static function main($args) {
Sequence::of([new Wall('My Team', Types::$CLOSED), new Wall('Developers', Types::$OPEN)])
->map(function($wall) {
if (Types::$OPEN === $wall->type()) {
return 'Open walls like '.$wall->name().' are great';
} else {
return 'Closed walls make sense sometimes, e.g. for '.$wall->name();
}
})
->each('util.cmd.Console::writeLine')
;
}
}
@thekid
Copy link
Author

thekid commented Jan 17, 2015

The Problem

I don't like the if statement.

Side note: The line static function __static() { Types::__static(); } is necessary as we're using inline-declared classes Types and Wall that the classloader doesn't really know about.

@thekid
Copy link
Author

thekid commented Jan 17, 2015

Idea #1

Introduce a match / when mini-DSL:

Sequence::of([new Wall('My Team', Types::$CLOSED), new Wall('Developers', Types::$OPEN)])
  ->map((new Match('Wall::type'))
    ->when(Types::$OPEN, function($wall) { return 'Open walls like '.$wall->name().' are great'; })
    ->when(Types::$CLOSED, function($wall) { return 'Closed walls make sense sometimes, e.g. for '.$wall->name(); })
  )
  ->each('util.cmd.Console::writeLine')
;
  • ✅ Reads well
  • ✅ Default handling of unhandled values = fail early
  • ✅ Would be extensible with other criteria, e.g. using something like isEqualTo and isInstanceOf methods instead of when.
  • ◻️ Performance worse than if - could be mitigated by using map backing for enum usecase

@thekid
Copy link
Author

thekid commented Jan 18, 2015

See https://github.com/xp-forge/match for the API itself and the performance figures

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment