2009/1/21 Tom Cloyd <tomcloyd / comcast.net>:
> Stefan Lang wrote:
>>
>> 2009/1/21 RK Sentinel <sentinel.2001 / gmx.com>:
>>
>>>
>>> I'm writing my first largeish app. One issue that gets me frequently is
>>> this:
>>>
>>> I define a string in one class. Some other class references it, and
>>> modifies it. I (somehow) expected that when another referer modifies the
>>> reference, ruby would automatically dup() the string.
>>>
>>> Anyway, through trial and error, I start dup()'ing strings myself. I am
>>> aware of freeze().
>>>
>>> But would like to know how others handle this generally in large apps.
>>>
>>> - Do you keep freezing Strings you make in your classes to avoid
>>> accidental change
>>>
>>> - Do you habitually dup() your string ?
>>>
>>> Is there some clean way of handling this that I am missing.
>>>
>>
>> This is a well known "problem" with all languages that
>> have mutable strings. The solution is simple:
>>
>> * Use destructive string methods only after profiling has shown
>>  that string manipulation is the bottleneck.
>>
>> * Don't mutate a string after passing it across encapsulation
>>  boundaries.
>>
>> Freezing certain strings can be beneficial in the same way
>> assertions are, habitually duping strings is a bad practice, IMO.
>>
>> Stefan
>>
>>
>>
>
> 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.
>
> What am I missing here?

There's nothing wrong with it if the purpose of the method
is to manipulate the string and it's documented clearly.

Every rule has exceptions :-)

Stefan