Issue #18035 has been updated by duerst (Martin D=FCrst).


This is mostly just a generic comment that may not be very helpful, but I c=
an only say that I fully agree. Even before talking about parallel stuff (t=
hread/fiber), knowing some object is frozen can be of help when optimizing.

One thing that might be of interest is that in a method chain, a lot of the=
 intermediate objects (e.g. arrays, hashes) may be taken to be immutable be=
cause they are just passed to the next method in the chain and never used o=
therwise (but in this case, it's just the top object that's immutable, not =
necessarily the components, which may be passed along the chain).

----------------------------------------
Bug #18035: Introduce general model/semantic for immutable by default.
https://bugs.ruby-lang.org/issues/18035#change-92843

* Author: ioquatix (Samuel Williams)
* Status: Open
* Priority: Normal
* Backport: 2.6: UNKNOWN, 2.7: UNKNOWN, 3.0: UNKNOWN
----------------------------------------
It would be good to establish some rules around mutability, immutability, f=
rozen, and deep frozen in Ruby.

I see time and time again, incorrect assumptions about how this works in pr=
oduction code. Constants that aren't really constant, people using `#freeze=
` incorrectly, etc.

I don't have any particular preference but:

- We should establish consistent patterns where possible, e.g.
  - Objects created by `new` are mutable.
  - Objects created by literal are immutable.

We have problems with how `freeze` works on composite data types, e.g. `Has=
h#freeze` does not impact children keys/values, same for Array. Do we need =
to introduce `freeze(true)` or `#deep_freeze` or some other method?

Because of this, frozen does not necessarily correspond to immutable. This =
is an issue which causes real world problems.

I als propose to codify this where possible, in terms of "this class of obj=
ect is immutable" should be enforced by the language/runtime, e.g.


```ruby
module Immutable
  def new(...)
    super.freeze
  end
end

class MyImmutableObject
  extend Immutable

  def initialize(x)
    @x =3D x
  end
  =

  def freeze
    return self if frozen?
    =

    @x.freeze
    =

    super
  end
end

o =3D MyImmutableObject.new([1, 2, 3])
puts o.frozen?
```

Finally, this area has an impact to thread and fiber safe programming, so i=
t is becoming more relevant and I believe that the current approach which i=
s rather adhoc is insufficient.

I know that it's non-trivial to retrofit existing code, but maybe it can be=
 done via magic comment, etc, which we already did for frozen string litera=
ls.



-- =

https://bugs.ruby-lang.org/

Unsubscribe: <mailto:ruby-core-request / ruby-lang.org?subject=3Dunsubscribe>
<http://lists.ruby-lang.org/cgi-bin/mailman/options/ruby-core>