Getting carried away when writing code like prose, or not
We all know how indexes work. The first item is 0
, the second item is 1
; CS49-topic;
So really, there's no doubt about what this code means:
$blocks[0]['name'] === 'acme/image';
Also, no doubt about what this one means:
$blocks[1]['name'] === 'acme/image';
Let's suppose that's really the gist of the "code": checking if the "name" of the first or second "block" matches "acme/image".
I think having a conditional like this is okay:
if ($blocks[0]['name'] === 'acme/image') {
return 'something';
}
if ($blocks[1]['name'] === 'acme/image') {
return 'something else';
}
It just gets the job done.
Extracting to a variable or constant the "block type" would be a slight improvement:
const IMAGE_BLOCK = 'acme/image';
if ($blocks[0]['name'] === IMAGE_BLOCK) {
return 'something';
}
if ($blocks[1]['name'] === IMAGE_BLOCK) {
return 'something else';
}
Capturing and hiding away the "block structure" is an idea to explore:
function blockNameMatches(array $block, string $name): bool
{
return $block['name'] === $name;
}
if (blockNameMatches($blocks[0], IMAGE_BLOCK)) {
return 'something';
}
Building on top of these low-level functions could bring some clarity and specificity:
function isBlockAnImageBlock(array $block): bool
{
return blockNameMatches($block, IMAGE_BLOCK);
}
if (isBlockAnImageBlock($blocks[0])) {
return 'something';
}
However weird it might seem at first sight, using constants in place of those indexes makes things more readable to me:
const FIRST = 0;
const SECOND = 1;
if (isBlockAnImageBlock($blocks[FIRST])) {
return 'something';
}
if (isBlockAnImageBlock($blocks[SECOND])) {
return 'something else';
}
But somehow, for big numbers, like FIVE_HUNDRED_AND_TWENTY_TWO
, it no longer works.
And, of course, there's no limit; we can go even further:
function isFirstBlockAnImageBlock(array $blocks): bool
{
return isBlockAnImageBlock($blocks[FIRST]);
}
if (isFirstBlockAnImageBlock($blocks)) {
return 'something';
}
if (isSecondBlockAnImageBlock($blocks)) {
return 'something else';
}
Is it better now or worse? When was good enough?
I like that there are no straightforward answers to these questions.