Tell Don't Ask
Published on

OOP syntax is not OOP - Code review #1


This code was posted as an example on how to use comments to annotate how the structure looks like at each point of the conversion process.

// Looks like: ['foo' => 'bar', 'abc' => 'xyz']
$trackedData = $model->getTrackedData();

$records = [];
foreach ($trackedData as $key => $value) { // 'foo' => 'bar'
  $records[] = ['key' => $key, 'value' => $value];

// $records looks like: [['key' => 'foo', 'value' => 'bar'], ['key' => 'abc', 'value' => 'xyz']]

Problem with this code is that it is procedural code with OOP syntax.

Someone already suggested a way better approach.

class KeyValue
  public static function restructure(array $items): array
    return collect($items)
      ->map(fn (string $value, string $key): array => compact('key', 'value'))

Creator of this snippet wrote:

Encapsulated and reusable.

And we agree with it. If we ignore the naming of the class then even the creator of it forgot to mention key point for it. This code is testable.