DusanKasan / Knapsack

Collection pipeline library for PHP
http://dusankasan.github.io/Knapsack/
MIT License
536 stars 56 forks source link

Use correctly find() with object #44

Closed roukmoute closed 7 years ago

roukmoute commented 7 years ago

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

jdreesen commented 7 years ago

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 ;)

roukmoute commented 7 years ago

You're right :clap: