Re: [RFC] Immutable variables and objects

From: Date: Fri, 30 Jan 2015 15:07:28 +0000
Subject: Re: [RFC] Immutable variables and objects
References: 1  Groups: php.internals 
Request: Send a blank email to [email protected] to get a copy of this message
Hi Alexander,

> On 30 Jan 2015, at 13:07, Alexander Lisachenko <[email protected]> wrote:
> 
> Hello, internals!
> 
> Today I was looking at PSR-7 and discovered this part of code:
> 
> $body = new StringStream(json_encode(['tasks' => [
>    'Code',
>    'Coffee',
> ]]));;
> $request = $baseRequest
>    ->withUri($uri->withPath('/tasks/user/' . $userId))
>    ->withMethod('POST')
>    ->withHeader('Content-Type' => 'application/json')
>    ->withBody($body);
> $response = $client->send($request);
> 
> What is wrong here? Emulated immutability. All methods will create a
> separate instance of request, so
> $baseRequest->withUri()->withMethod()->withHeader()->withBody() will create
> total 5 object instances. It's a memory overhead and time consumption for
> each method call.

Yes, I also think this is unfortunate.

> What I want to discuss is true immutability flag for variables and
> parameters. There are a lot of languages that use "final" or "const"
> keywords to prevent modification of variables. We can use this approach by
> extending language syntax as following:

This approach wouldn’t solve the problem you’re describing. You *still* need to produce a new
request object, because the request object is immutable. The mutability of its *properties* isn’t
the issue.

If you want to avoid creating five different objects, you’d need to implement value-type objects
that are passed by value and use copy-on-write. Basically, you’d need to re-add PHP 4 style
classes.

Thanks.
--
Andrea Faulds
http://ajf.me/






Thread (23 messages)

« previous php.internals (#81432) next »