Why use Ruby's attr_accessor, attr_reader and attr_writer?

前端 未结 5 1053
走了就别回头了
走了就别回头了 2020-11-22 14:51

Ruby has this handy and convenient way to share instance variables by using keys like

attr_accessor :var
attr_reader :var
attr_writer :var

5条回答
  •  隐瞒了意图╮
    2020-11-22 15:28

    Not all attributes of an object are meant to be directly set from outside the class. Having writers for all your instance variables is generally a sign of weak encapsulation and a warning that you're introducing too much coupling between your classes.

    As a practical example: I wrote a design program where you put items inside containers. The item had attr_reader :container, but it didn't make sense to offer a writer, since the only time the item's container should change is when it's placed in a new one, which also requires positioning information.

提交回复
热议问题