Last active
August 29, 2015 14:16
-
-
Save johnkary/a64363bac55c90a1ca97 to your computer and use it in GitHub Desktop.
Example of using tuples instead of array key-value pairs
This file contains hidden or 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
class BuildReport | |
{ | |
private function getColumnHeaders() | |
{ | |
// Why do you need array keys if this array is private details? | |
// It's never exposed outside this class so you have full control of its format | |
return [ | |
['id' => 'first_name', 'label' => 'First Name'], | |
['id' => 'last_name', 'label' => 'Last Name'], | |
['id' => 'department', 'label' => 'Department'], | |
]; | |
} | |
public function render($records) | |
{ | |
foreach ($this->getColumnHeaders() as $header) { | |
$id = $header['id']; | |
$label = $header['label']; | |
// Do something with $id and label ... | |
} | |
} | |
} |
This file contains hidden or 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
class BuildReport | |
{ | |
private function getColumnHeaders() | |
{ | |
// If you need to change the data, the changes are confined to this class | |
return [ | |
['first_name', 'First Name'], | |
['last_name', 'Last Name'], | |
['department', 'Department'], | |
]; | |
} | |
public function render($records) | |
{ | |
// PHP >= 5.5 -- This is the shortest thanks to this feature in 5.5 https://wiki.php.net/rfc/foreachlist | |
foreach ($this->getColumnHeaders() as list($id, $label)) { | |
// Do something with $id and label ... | |
} | |
// PHP < 5.5 -- This is slightly more code if you're running 5.4 or older | |
foreach ($this->getColumnHeaders() as $header) { | |
list($id, $label) = $header; | |
// Do something with $id and label ... | |
} | |
} | |
} |
Perhaps this is a bad example, but what do you do when you later on you need to add meta-data to each of these? ex: a class name to certain headers
It seems to me the weakness of a tuple is that by its very definition it is hard-coded to be a pair. I ccan see other examples where this could be desirable - key:values where you might actually like to enforce that pairing, but if that is not the case, you seem to lock yourself into a structure purely because you feel it "looks like nicer code"
Have I completely missed your point?
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@archwisp
$header->id
isn't bad but is equal in readability for me compared to$header['id']
. I'm not sure on the performance impact from casting an array to an object, but doing so seems unnecessary if we're not gaining in readability inside our foreach.