ideas icon indicating copy to clipboard operation
ideas copied to clipboard

Why Taylor uses tap instead of just a simple assignment

Open akbarjimi opened this issue 3 years ago • 5 comments

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; 

akbarjimi avatar Mar 04 '21 17:03 akbarjimi

This has absolute nothing to do with ideas for Laravel.

stephan-v avatar Mar 04 '21 18:03 stephan-v

This has absolute nothing to do with ideas for Laravel.

Yeah, you're right.

Could you please answer my question?

akbarjimi avatar Mar 04 '21 23:03 akbarjimi

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

Blacksky13 avatar Mar 07 '21 09:03 Blacksky13

@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

akbarjimi avatar Mar 07 '21 14:03 akbarjimi

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.

garygreen avatar May 27 '21 12:05 garygreen