Tom Cloyd
1/21/2009 10:09:00 PM
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?
Thanks, if you can help me out!
Tom
--
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Tom Cloyd, MS MA, LMHC - Private practice Psychotherapist
Bellingham, Washington, U.S.A: (360) 920-1226
<< tc@tomcloyd.com >> (email)
<< TomCloyd.com >> (website)
<< sleightmind.wordpress.com >> (mental health weblog)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~