将克隆对象的所有责任转移给库的用户是否正确?
我对这个问题不太了解,所以我决定在这里问。假设我们有一些 Ruby(或任何其他传递引用脚本语言)的“库”:
class Moo
attr_accessor :bar
def initialize
self
end
end
a = 'a string'
b = Moo.new
b.bar = a
b.bar
显然与 a
是同一个对象。
在所有情况中保留它是否正确,以便需要它们分开的程序员手动进行克隆?这是我最终想到的唯一理智的想法。
I'm not that knowledgeable in this matter so I decided to ask here. Let's say we have some 'library' in Ruby (or any other pass by reference scripting language):
class Moo
attr_accessor :bar
def initialize
self
end
end
a = 'a string'
b = Moo.new
b.bar = a
b.bar
will obviously be the same object as a
.
Is it right to leave it as it is in all cases so programmer who need them separate will do cloning manually? That's the only sane idea I ended up with.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
遵循最小惊喜原则,在您创建时维护对指定对象的引用是正确的已经做了。
如果您在内部
重复
了分配给bar
的对象,那么您的库的使用者将会极度感到沮丧谁想要bar
引用相同的对象。顺便说一句,
definitialize() self end
是完全不必要的,因为它与默认的initialize
相同。Following the principle of least surprise, it is correct to maintain the reference to the assigned object as you've done.
If you did internally
dup
the object assigned tobar
, it would be extremely frustrating to a consumer of your library who wantedbar
to refer to the identical object.As a side note,
def initialize() self end
is completely unnecessary as it is identical to the defaultinitialize
.