Issue #12334 has been updated by Brady Wied.


Here is an example:

~~~
class Foo
  attr_reader :foo

  def initialize
    @foo = 123
  end

  def accidental_mutate
    @foo = 456 # Ruby doesn't give me any way to prevent this as of now
  end
end

class Foo
  attr_readonly :foo # one way, see initializer

  def initialize
    # another way
    readonly @foo = 123
  end

  def accidental_mutate
    @foo = 456 # Ruby could throw an error here and prevent me from doing this
  end
end


~~~

----------------------------------------
Feature #12334: Final/Readonly Support for Fields / Instance Variables
https://bugs.ruby-lang.org/issues/12334#change-58424

* Author: Brady Wied
* Status: Rejected
* Priority: Normal
* Assignee: 
----------------------------------------
This sort of relates to https://bugs.ruby-lang.org/issues/11911

C# through 'readonly' and Java through 'final' variables/fields allow me to only allow assigning a field in the initializer. It might be nice to embrace some controlled mutation by having this feature in Ruby. Sometimes its tempting in other methods to reassign a field but you really want to control that from the initializer.

Freezing targets a different problem by controlling what I can mutate within that field's object. The two can compliment each other but I see them as each solving a different problem. I know it's possible to freeze an entire instance of a class and not allow reassigning the field that way, but then I'm in an all or none situation where I can't have controlled mutation.



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

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