From: Brian Candler Date: 2009-01-22T17:15:48+09:00 Subject: Re: String doesnt auto dup on modification Tom Cloyd wrote: > 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. No, I'm not saying this. Sometimes it's useful to modify the string passed in: def cleanup!(str) str.strip! str.replace("default") if str.empty? end However I'd say this is not the usual case. More likely I'd write def cleanup(str) str = str.strip str.empty? "default" : str end > 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. Regards, Brian. -- Posted via http://www.ruby-forum.com/.