laravel / ideas

Issues board used for Laravel internals discussions.
938 stars 28 forks source link

Why Taylor uses tap instead of just a simple assignment #2522

Open akbarjimi opened 3 years ago

akbarjimi commented 3 years ago

In this PR Taylor Otwell in the fetch method uses tap for empting the buffer instead of just a simple assignment why he do this?

        return tap($this->buffer, function () {
            $this->buffer = '';
        });

instead of this

        $this->buffer = '';
        return $this->buffer; 
stephan-v commented 3 years ago

This has absolute nothing to do with ideas for Laravel.

akbarjimi commented 3 years ago

This has absolute nothing to do with ideas for Laravel.

Yeah, you're right.

Could you please answer my question?

Blacksky13 commented 3 years ago

@akbarjimi Please have a look - https://medium.com/@taylorotwell/tap-tap-tap-1fc6fc1f93a6

I think the idea behind it is to avoid following peace of code:

$this->buffer = '';

return $this;
akbarjimi commented 3 years ago

@akbarjimi Please have a look - https://medium.com/@taylorotwell/tap-tap-tap-1fc6fc1f93a6

I think the idea behind it is to avoid following peace of code:

$this->buffer = '';

return $this;

Thank you so much. I read that article and saw in the comments that many users like me did not understand the reason for such a function. I think Taylor is very much inspired by Ruby

garygreen commented 3 years ago

I too question the over-use of tap() it is quite an opinionated design decision. My main concern is it being used in core part of Laravel in complex loops, and potentially slowing down applications unnecessarily, probably not by much though.

It's mainly used to proxy the result of a function and return the original passed value. So if your ->update() function returned a boolean, you could use tap and have it return the original object and continue the chain. Better explained here

In the OPs example it definitely seems overkill to use tap here. It's a personal preference though.

I try to avoid closures and heavy indenting, so not really a fan of tap. Also it increases the call stack of your application, makes it harder to debug. Overall I avoid it if I can.