ideas
ideas copied to clipboard
Why Taylor uses tap instead of just a simple assignment
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;
This has absolute nothing to do with ideas for Laravel.
This has absolute nothing to do with ideas for Laravel.
Yeah, you're right.
Could you please answer my question?
@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 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
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.