4 ms·
That gives you immutability on that instance, but the benefits are diminished since the language is not immutable-first. If it were, I’d expect f2.setY(30) to
by filoeleven 5y ago
That gives you immutability on that instance, but the benefits are diminished since the language is not immutable-first. If it were, I’d expect f2.setY(30) to return a new immutable instance of Foo with x == 20 and y == 30. As it stands, there’s not a reliable way to get “an immutable Foo instance with everything the same except for y, which has this new value.”
For a class with two properties, you can make a new constructor that initializes both, though it’s a bit unwieldy. It becomes unworkable when you have five or ten properties. A more data-oriented approach would be to use a key/value map, and have standard functions to “update” map members by returning new maps with the “updated” value(s). Those libraries probably exist for C++, but you have to enforce their use, whereas languages that are built around those concepts provide stronger guarantees from the outset.