Re: RFC - Immutable classes

From: Date: Sat, 10 Sep 2016 18:01:44 +0000
Subject: Re: RFC - Immutable classes
References: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18  Groups: php.internals 
Request: Send a blank email to internals+get-95902@lists.php.net to get a copy of this message
On Sat, Sep 10, 2016 at 7:49 PM, Niklas Keller <me@kelunik.com> wrote: > 2016-09-10 19:41 GMT+02:00 Silvio Marijić <marijic.silvio@gmail.com>: > > > @Fleshgrinder, > > > > While I'm not sure at the moment about CoW, I can agree that we should > add > > immutable keyword as a interface modifier to make sure all classes > > implementing must be immutable. > > > As interfaces can't have member variables, that doesn't make sense to me. > It still makes sense from a consumer perspective, so having the restriction in the contract is quite good. If you accept a Number, you expect to be able to serialize/de-serialize it, and you expect it to be "locked", immutable. If you let an implementation of Number to have mutable state in, then you break all the code that relies on Number. Note that it is still possible to break this though, so maybe we'd need some other modifiers about behavior too (pure function modifier?) immutable interface Number { public function toFloat() : float; } immutable class RandomNumber implements Number { public function toFloat() : float { return (float) random_int(1, 100000); /* yo, look at my global mutable hidden state! */ } } Requiring immutable values in consumers will likely improve code quality/safety and reduce dangerous assumptions, and it will probably also allow for optimizations in the engine later on. Marco Pivetta http://twitter.com/Ocramius http://ocramius.github.com/

« previous php.internals (#95902) next »