If this is an utterly dumb question, just ignore it. However, I AM
perplexed by this response. Here’s why:

I thought it was OK for an object to receive input, and output a
modified version of same. If they don’t get to do that, their use seems
rather limited. In my current app, I create a log object, and various
classes write to it. I don’t create new objects every time I want to add
a log entry. Why would I do that? Makes no sense to me. I might want to
do exactly the same thing to a string. You seem to be saying this is bad
form. I can see that there are cases where you want the string NOT to be
modified, but you see to be saying that to modify the original string at
all is bad.

It makes perfect sense to me to pass an object (string, in this case)
across an encapsulation boundary specifically to modify it.

If this is an utterly dumb question, just ignore it. However, I AM
perplexed by this response. Here’s why:
i agree with you.

I have objects that get a string, process/clean it for printing/display.
(That is the whole purpose of centralizing data and behaviour into
classes.)

Remembering I must not modify it is a big mental overhead and results
in strange things that I spend a lot of time tracking, till I find out
— oh no the string got mutated over there. Now I must start dup()'ing
it – okay, where all should I dup it ?

To the previous poster - yes, one does not have to use dup. One can
create a new string by changing the method from say gsub! to just
gsub() and take the return value. I include such situations when i say
dup().

Of course there is no contract to enforce this, but in many cases it
would be considered bad manners to modify an object which is passed in
as an argument.

Depends: for example, if you have a method that is supposed to dump
something to a stream (IO and friends) which only uses << you can as
well use String there.

If you only read the object, then it doesn’t matter.

That may be true for methods but if you need to store a String as
instance variable then I tend to dup it if the application is larger.
You can even automate conditional dup’ing by doing something like this

I thought it was OK for an object to receive input, and output a
modified version of same.

Do you mean “return the same object reference, after the object has been
modified”, or “return a new object, which is a modified copy of the
original”?

If they don’t get to do that, their use seems
rather limited. In my current app, I create a log object, and various
classes write to it. I don’t create new objects every time I want to add
a log entry. Why would I do that? Makes no sense to me.

I’d consider a logger object as a sort of stream. You’re just telling
the logger to “do” something every time you send it a message; you’re
not really telling it to change into a different sort of logger. (Of
course, if the logger is logging to an underlying string buffer, then
changing that buffer is a desired side effect of logging, but the logger
itself is still the same)

I might want to
do exactly the same thing to a string. You seem to be saying this is bad
form. I can see that there are cases where you want the string NOT to be
modified, but you see to be saying that to modify the original string at
all is bad.

It makes perfect sense to me to pass an object (string, in this case)
across an encapsulation boundary specifically to modify it.

Yes, in some cases it does, and it’s up to you to agree the ‘contract’
in your documentation that that’s what you’ll do. I’m not saying it’s
forbidden.

But this seems to be contrary to your original question, where you were
saying you were defensively dup’ing strings, on both input and output,
to avoid cases where they get mutated later by the caller or some other
object invoked by the caller.

I’m saying to avoid this problem, the caller would not pass a string to
object X, and then mutate it (e.g. by passing it to another object Y
which mutates it). And in practice, I find this is not normally a
problem, because normally objects do not mutate strings which are passed
into them as arguments.

This is not a hard and fast rule. It’s just how things work out for me
in practice. It depends on your coding style, and whether you’re coding
for yourself or coding libraries to be used by other people too.

I’d vote against this. It looks to me like a great way to confuse users
and complicate interfaces. I’d rather go towards transparency.
Generally I’d not mutate arguments, only the receiver. If there’s a
valid case to mutate an argument, it should be documented and evident.
The user then has to provide a duplicate if he still needs the original.

Beware: this may not solve your problem. It will work if the passed-in
object is itself a String, but not if it’s some other object which
contains Strings.

Try:

a = [“hello”, “world”]
b = a.dupf
b[0] << “XXX”
p a

However, deep-copy is an even less frequently seen solution.

In response to the prev post by Brian, yes its a library for use by
others.

It’s hard to provide concrete guidance without knowing what this library
does, but it sounds like it builds some data structure which includes
the string passed in.

I believe that a typical library is behaving correctly if it just stores
a reference to the string.

If a problem arises because the caller is later mutating that string
object, this could be considered to be a bug in the caller. The caller
can fix this problem by dup’ing the string at the point when they pass
it in, or dup’ing it later before changing it.

Again, this is not a hard-and-fast rule. Sometimes defensive dup’ing is
reasonable. For example, Ruby’s Hash object has a special-case for
string keys: if you pass in an unfrozen string as a hash key, then the
string is dup’d and frozen before being used as the key.

This may (a) lead to surprising behaviour, and (b) doesn’t solve the
general problem (*). However strings are very commonly used as hash
keys, and they are usually short, so it seems a reasonable thing to do.

Regards,

Brian.

(*) In the case of a hash with string keys, if you mutated one of those
keys then it could end up being on the wrong hash chain, and become
impossible to retrieve it from the hash using hash[“key”]

So it’s a question of which of two behaviours is least undesirable:
objects disappearing from the hash because you forgot to call #rehash,
or hashes working “right” with string keys but “wrong” with other keys.

I guess I’ll just have to remember not to modify a string I take from
another class.

Or as was said earlier on: simply don’t use destructive string methods
unless you really have to. Pretend that all strings are frozen.

Yes, I did mention too somewhere to use gsub! etc with caution. Fine in
local variables, strings that are not exposed.

He says he modifies some object …and to his great surprise the object
indeed gets modified. Nice way of putting it. But this happened across objects, and I was
wondering whether there was some other solution to the problem which did
not require my having to remember not to modify a string taken from
elsewhere.

valid case to mutate an argument, it should be documented and evident.
The user then has to provide a duplicate if he still needs the original.

Not sure what you mean because the code makes sure that the argument
is not mutated.

Or did you mean “caller” when you wrote “I” above? There are
different policies to handle that as this thread has shown. Generally
I tend to follow the line that the caller is the owner of the object
unless otherwise stated. This also means that he is free to change it
at any time and consequently it is the responsibility of the receiver
to take whatever measures if he needs to make sure he keeps track of
the unmodified state.

IMHO this is a reasonable policy because if ownership passing would be
the default you would have to copy always as the caller if you need to
continue to work with the object - even if receivers just use the
object temporary and do not store references for longer. This would be
a waste of resources.

In practice this is usually not an issue for me so IMHO the discussion
has a strong “theoretical” aspect. OTOH it’s good to reason about
these things from time to time. Helps clarify some things and avoid
mistakes.

Thanks for all the helpful replies. Its my first venture: a widget
library.

Here’s an example: Sometimes a string is passed to a class, say, using
its set_buffer method (which is an optional method).

set_buffer just assigns it to @buffer. But deep within the class this
variable is being edited using insert() or slice!() (and this IS
necessary) since the widget is an editing widget. So its not so clear
when i added set_buffer method that this would happen.

As and when i discover such bugs in my code, I start adding dup(), and
yes sometimes these lines bomb when another datatype is passed (I had
asked this in a thread recently: respond_to? dup was passing, but the
dup was failing).

Yesterday, I had written an Action class which can be used to create a
menuitem or a button. The string used in the Action constructor can be
like “&Delete”.
Button and Menuitem remove the “&” using a slice!(). And i was wondering
why the second usage was failing to find the “&”.

Anyway, i realize its more my incompetence, and i must be careful with
destructive methods, but I just thought maybe there’s some other way to
do this, so i am not leaving it to my memory.

Thanks again for the helpful replies. The ruby community really rocks
when it comes helping others.