Is it right to move all responsibility for cloning objects to user of a library?
-
03-10-2019 - |
Question
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.
Solution
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
.