为什么要使用 Ruby 的 attr_accessor、attr_reader 和 attr_writer? [英] Why use Ruby's attr_accessor, attr_reader and attr_writer?

查看:40
本文介绍了为什么要使用 Ruby 的 attr_accessor、attr_reader 和 attr_writer?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Ruby 有这种方便且方便的方式,可以使用诸如

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

attr_accessor :var
attr_reader :var
attr_writer :var

如果我可以简单地使用attr_accessor,我为什么要选择attr_readerattr_writer?有没有像性能这样的东西(我怀疑)?我想是有原因的,否则他们不会制作这样的钥匙.

Why would I choose attr_reader or attr_writer if I could simply use attr_accessor? Is there something like performance (which I doubt)? I guess there is a reason, otherwise they wouldn't have made such keys.

推荐答案

您可以使用不同的访问器将您的意图传达给阅读您代码的人,并使编写无论公共 API 如何都能正常工作的类变得更容易被称为.

You may use the different accessors to communicate your intent to someone reading your code, and make it easier to write classes which will work correctly no matter how their public API is called.

class Person
  attr_accessor :age
  ...
end

在这里,我可以看到我可以同时读取和写入年龄.

Here, I can see that I may both read and write the age.

class Person
  attr_reader :age
  ...
end

在这里,我可以看到我可能只阅读了年龄.想象一下,它是由这个类的构造函数设置的,之后保持不变.如果有一个用于年龄的修改器(编写器),并且假设该年龄一旦设置就不会更改,那么编写该类时,调用该修改器的代码可能会导致错误.

Here, I can see that I may only read the age. Imagine that it is set by the constructor of this class and after that remains constant. If there were a mutator (writer) for age and the class were written assuming that age, once set, does not change, then a bug could result from code calling that mutator.

但幕后发生了什么?

如果你写:

attr_writer :age

翻译成:

def age=(value)
  @age = value
end

如果你写:

attr_reader :age

翻译成:

def age
  @age
end

如果你写:

attr_accessor :age

翻译成:

def age=(value)
  @age = value
end

def age
  @age
end

知道了这一点,这里有另一种思考方式:如果您没有 attr_... 助手,并且必须自己编写访问器,您会编写比类需要的更多的访问器吗?比如,如果只需要读取age,你会不会也写一个方法允许写入?

Knowing that, here's another way to think about it: If you did not have the attr_... helpers, and had to write the accessors yourself, would you write any more accessors than your class needed? For example, if age only needed to be read, would you also write a method allowing it to be written?

这篇关于为什么要使用 Ruby 的 attr_accessor、attr_reader 和 attr_writer?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆