attr vs attr_accessor

后端 未结 3 1347
无人及你
无人及你 2020-12-15 05:31

In Ruby there are four different getter and setter methods for instance variables, attr, attr_reader, attr_writer, and attr_acce

3条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-15 06:15

    If you look at the C code in Ruby 2.3.0, you will see that attr and attr_reader are actually doing the same thing (except for the deprecated code path). They are essentially equivalent functions.

    For me, the main differences are:

    attr is a bit easier to write down as it's shorter. I like the way it feels in the context of functional/immutable programming too (in those contexts, attr_writer and attr_accessor are irrelevant and thus using attr_reader feels verbose and redundant).

    attr with multiple instance variables makes it hard to document, except in very specific situations, e.g.

    # The coordinates in WGS84.
    attr :x, :y
    
    # The location name.
    attr :name
    
    # The popularity of the location.
    attr :popularity
    

    It would be harder to document :name and :popularity independently if they were on the same line attr :name, :popularity.

    Apart from that it boils down to personal preference. There is in practice no performance difference or any other difference.

提交回复
热议问题