[英]What is the difference between an instance method used to rename an object and a setter method?
If I want to rename my jedi
object below, why would I create an instance method named rename
that uses the setter method name=
?如果我想在下面重命名我的jedi
对象,为什么要创建一个名为rename
的实例方法,它使用 setter 方法name=
? Why not just use the setter method `name=' directly?为什么不直接使用setter方法`name='?
Why do this:为什么要这样做:
class Skywalker
attr_accessor :name
def initialize(name)
@name = name
end
def rename(new_name)
self.name = new_name
end
end
jedi = Skywalker.new('Anakin')
puts jedi.name
jedi.rename('Luke')
puts jedi.name
When you could just do this:当你可以这样做时:
class Skywalker
attr_accessor :name
def initialize(name)
@name = name
end
end
jedi = Skywalker.new('Anakin')
puts jedi.name
jedi.name = 'Luke'
puts jedi.name
Both code snippets above do the same thing, so I'm wondering if there is a situation where it would be useful to have the instance method rename
in addition to the setter method name=
.上面的两个代码片段都做同样的事情,所以我想知道是否存在除了 setter 方法name=
之外rename
实例方法有用的情况。 Because to me it looks like they are redundant.因为在我看来它们是多余的。
#rename
hides the implementation details. #rename
隐藏实现细节。 You expose a clean and explicit interface - an object can be renamed, but the caller doesn't have to care how it's done.您公开了一个干净而显式的接口——一个对象可以被重命名,但调用者不必关心它是如何完成的。 I would recommend to use attr_reader :name
instead of attr_accessor :name
to avoid exposing the setter.我建议使用attr_reader :name
而不是attr_accessor :name
以避免暴露 setter。
If you expose just #name=
you let the caller to change object internals.如果你只公开#name=
你让调用者改变对象内部。 It may cause the future changes harder (eg if you move name
to a separate object).它可能会导致未来的更改更加困难(例如,如果您将name
移动到一个单独的对象)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.