Re: [RFC] Data Classes

From: Date: Sat, 23 Nov 2024 15:43:31 +0000
Subject: Re: [RFC] Data Classes
References: 1 2  Groups: php.internals 
Request: Send a blank email to internals+get-126034@lists.php.net to get a copy of this message
On Sat, Nov 23, 2024, at 16:02, Eugene Sidelnyk wrote: > Hello > > If I remember correctly, the whole concept of "value" is fully described in DDD book > by Eric Evans. If that's the point of the RFC, I wonder of there's any point in not making > such classes immutable by default, and to keep only one instance of value object unique per given > set of properties in memory, thereby eliminating cloning altogether and optimizing the memory usage. > > > On Sat, Nov 23, 2024, 3:12 PM Rob Landers <rob@bottled.codes> wrote: >> __ >> Hello internals, >> >> Born from the Records RFC (https://wiki.php.net/rfc/records) discussion, I would like to >> introduce to you a competing RFC: Data Classes (https://wiki.php.net/rfc/dataclass). >> >> This adds a new class modifier: data. This modifier drastically changes how classes work, >> making them comparable by value instead of reference, and any mutations behave more like arrays than >> objects (by vale). If desired, it can be combined with other modifiers, such as readonly, to enforce >> immutability. >> >> I've been playing with this feature for a few days now, and it is surprisingly >> intuitive to use. There is a (mostly) working implementation available on GitHub >> (https://github.com/php/php-src/pull/16904) if you want to have a go at it. >> >> Example: >> >> data class UserId { public function __construct(public int $id) {} } >> >> $user = new UserId(12); >> // later >> $admin = new UserId(12); >> if ($admin === $user) { // do something } // true >> >> Data classes are true value objects, with full copy-on-write optimizations: >> >> data class Point { >> public function __construct(public int $x, public int $y) {} >> public function add(Point $other): Point { >> // illustrating value semantics, no copy yet >> $previous = $this; >> // a copy happens on the next line >> $this->x = $this->x + $other->x; >> $this->y = $this->y + $other->y; >> assert($this !== $previous); // passes >> return $this; >> } >> } >> >> I think this would be an amazing addition to PHP. >> >> Sincerely, >> >> — Rob Hello! Don't forget to bottom-post! > I wonder of there's any point in not making such classes immutable by default, and to keep > only one instance of value object unique per given set of properties in memory, thereby eliminating > cloning altogether and optimizing the memory usage. This was the entire point of the records RFC ;) it was immutable by default, but people were wondering what it would look like if it were more 'composable' vs. 'dedicated syntax'. — Rob

« previous php.internals (#126034) next »