将克隆对象的所有责任转移给库的用户是否正确?

发布于 2024-09-01 23:47:57 字数 323 浏览 5 评论 0原文

我对这个问题不太了解,所以我决定在这里问。假设我们有一些 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

虚拟世界 2024-09-08 23:47:57

遵循最小惊喜原则,在您创建时维护对指定对象的引用是正确的已经做了。

如果您内部重复了分配给bar的对象,那么您的库的使用者将会极度感到沮丧谁想要 bar 引用相同的对象。

> class Moo
>  attr_accessor :bar
> end
=> nil
> a = 'a string'
=> "a string"
> b = Moo.new
=> #<Moo:0x2bfd238>
> b.bar = a
=> "a string"
> a.upcase!
=> "A STRING"
> b.bar # should be uppercase as expected since `a` was modified *in-place*
=> "A STRING"
> b.bar = a.dup # now modifications to `a` will not affect `bar`
=> "A STRING"
> a.downcase!
=> "a string"
> b.bar
=> "A STRING"

顺便说一句,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 to bar, it would be extremely frustrating to a consumer of your library who wanted bar to refer to the identical object.

> class Moo
>  attr_accessor :bar
> end
=> nil
> a = 'a string'
=> "a string"
> b = Moo.new
=> #<Moo:0x2bfd238>
> b.bar = a
=> "a string"
> a.upcase!
=> "A STRING"
> b.bar # should be uppercase as expected since `a` was modified *in-place*
=> "A STRING"
> b.bar = a.dup # now modifications to `a` will not affect `bar`
=> "A STRING"
> a.downcase!
=> "a string"
> b.bar
=> "A STRING"

As a side note, def initialize() self end is completely unnecessary as it is identical to the default initialize.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文