2020-12-29 21:36 GMT, Rowan Tommins <rowan.coll...@gmail.com>: > On 29/12/2020 10:28, Olle Härstedt wrote: >> I just want to mention that immutability might be applied too >> liberally in the current discourse, and in some cases, what you really >> want is*non-aliasing*, that is, uniqueness, to solve problems related >> to immutability. I think methods like `withX` is an anti-pattern, in >> fact, and a symptom that you do not*really* want immutability, but >> rather uniqueness, at least in some cases. > > > Hi Olle, > > I'm afraid I don't follow what you mean by "non-aliasing" and > "uniqueness" here. Could you clarify, perhaps with some examples? > > Cheers, > > -- > Rowan Tommins > [IMSoP] >
Wikipedia has an article about aliasing: https://en.wikipedia.org/wiki/Aliasing_(computing) Also relevant: https://en.wikipedia.org/wiki/Uniqueness_type Uniqueness is when you only allow _one_ reference to an object (or bucket of memory). $a = new A(); $b = $a; // Both $a and $b point to the same place in memory, so you have an alias Uniqueness and immutability solves similar problems (at least in a GC language like PHP): Spooky action at a distance, fragile composition, rep exposure. The are more advanced systems of ownership than just uniqueness, e.g. Universe Types, but let's ignore that for now. https://www.researchgate.net/publication/221321963_Ownership_transfer_in_Universe_Types Uniqueness has the benefit of being more performant than immutability, since it leads to less memory copy (but of course it's not certain this performance gain matters in PHP programs). You can compare a builder pattern with immutability vs non-aliasing (uniqueness): ``` // Immutable $b = new Builder(); $b = $b->withFoo()->withBar()->withBaz(); myfun($b); // $b is immutable, so $b cannot be modified by myfun() return $b; ``` ``` // Uniqueness $b = new Builder(); // class Builder is annotated as non-aliasing/unique $b->addFoo(); $b->addBar(); $b->addBaz(); myfun(clone $b); // HAVE TO CLONE TO NOT THROW EXCEPTION. return $b; ``` The guarantee in both above snippets is that myfun() DOES NOT modify $b before returning it. BUT with immutability, you have to copy $b three times, with uniqueness only one. That's why I think ownership system merits some attention, not ONLY immutability. :) Unfortunately, it can take a looong time to force new concepts like these into common discourse. Rust helps, obviously. The language Clean has opt-in uniqueness (I need to read up more on it, tho). Linear types in e.g. Haskell is also related (but is both more complex and more powerful). I would like to add an annotation to Psalm, like @psalm-no-alias, because this is also needed to make type-state sane. But, didn't do much yet, only some brain farting. :) Olle -- PHP Internals - PHP Runtime Development Mailing List To unsubscribe, visit: https://www.php.net/unsub.php