Last active
August 29, 2015 14:17
-
-
Save mageekguy/0bd0a5be9632ff1b62e0 to your computer and use it in GitHub Desktop.
Immutability vs. mutability
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
interface console | |
{ | |
function newData($data); | |
function noMoreData(); | |
function dataGeneratorIs(dataGenerator $dataGenerator); | |
} | |
interface dataGenerator | |
{ | |
function consoleIs(console $console); | |
} | |
class mutableConsole implements console | |
{ | |
private | |
$data | |
; | |
function newData($data) | |
{ | |
$this->data .= $data; | |
return $this; | |
} | |
function noMoreData() | |
{ | |
echo $this->data . PHP_EOL; | |
} | |
function dataGeneratorIs(dataGenerator $dataGenerator) | |
{ | |
$dataGenerator->consoleIs($this); | |
return $this; | |
} | |
} | |
class immutableConsole implements console | |
{ | |
private | |
$data | |
; | |
function newData($data) | |
{ | |
$console = new self; | |
$console->data = $this->data . $data; | |
return $console; | |
} | |
function noMoreData() | |
{ | |
echo $this->data . PHP_EOL; | |
} | |
function dataGeneratorIs(dataGenerator $dataGenerator) | |
{ | |
$dataGenerator->consoleIs($this); | |
return $this; | |
} | |
} | |
class numberGenerator implements dataGenerator | |
{ | |
function consoleIs(console $console) | |
{ | |
foreach (range(1, 10) as $number) | |
{ | |
$console->newData($number); | |
} | |
return $this; | |
} | |
} | |
$numberGenerator = new numberGenerator; | |
(new mutableConsole)->dataGeneratorIs($numberGenerator)->noMoreData(); | |
(new immutableConsole)->dataGeneratorIs($numberGenerator)->noMoreData(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment