DusanKasan/Knapsack

Use correctly find() with object

Closed this issue · 2 comments

Hi!

I have originaly this part of code:

public function speed(): ?float
{
    /** @var AdditionalInformation $additionalEventInfo */
    foreach ($this->additionalEventInfo as $additionalEventInfo) {
        if ($additionalEventInfo->name() === 'Speed') {
            return (float) $additionalEventInfo->value();
        }
    }

    return null;
}

I've "translated" this code with Knapsack:

public function speed(): ?float
{
    $speed = Collection::from($this->additionalEventInfo)
        ->find(
            function (AdditionalInformation $additionalInformation) {
                return $additionalInformation->name() === 'Speed';
            }
        )
    ;

    if ($speed instanceof AdditionalInformation) {
        return (float) $speed->value();
    }

    return null;
}

Finally, I don't like this code.
It is not really more readable that original.

Is it a better solution?

Thanks

Well, you could write it like this, for example:

public function speed(): ?float
{
	$isSpeedInformation = function (AdditionalInformation $additionalInformation) {
		return $additionalInformation->name() === 'Speed';
	};

	$speedInformation = find($this->additionalEventInfo, $isSpeedInformation);

	return $speedInformation ? (float) $speedInformation->value() : null;
}

If you think that's more readable ;)

You're right 👏