[REBOL] Re: On mutability and sameness
From: joel:neely:fedex at: 17-Jun-2001 12:36
Hi, Paul,
Paul Tretter wrote:
> Ok, I have read these threads but since I'm new to
> programming I know not what is meant by the word "mutable".
> Can someone define this please.
>
I'll try to offer a definition without stepping on any
land mines...
Mutable: capable of being changed; read/write
Immutable: incapable of being changed; read-only
In REBOL, strings are mutable. Therefore, if I have set
a variable to a string, as in:
>> msg: "Hi, Paul" == "Hi, Paul"
I can *mutate* or modify the value of that string, as in:
>> append msg "!" == "Hi, Paul!"
>> msg == "Hi, Paul!"
APPEND "goes through" the variable to get to the string,
and changes the string itself.
That's different from starting with a string:
>> msg: "Hi, Paul" == "Hi, Paul"
and merely *replacing* it with a different string.
>> msg: "Hi, Paul!" == "Hi, Paul!"
>> msg == "Hi, Paul!"
In REBOL, integers are immutable. If I have set a variable
to an integer, as in:
>> a: 42 == 42
I can't modify the integer itself, but can *only* replace it
with another integer:
>> a: a + 1 == 43
Even if the new integer were calculated from the value of the
old one, I'm still *replacing*, because the above expression
means
set A to the result of evaluating A and adding one
Even though I used the variables MSG and A in the examples
above, mutability/immutability are not about variables, but
about the values themselves. For example, we could have done:
>> blk: ["Hi, Paul" 42] == ["Hi, Paul" 42]
>> append first blk "!" == "Hi, Paul!"
>> blk/2: blk/2 + 1 == ["Hi, Paul!" 43]
>> blk == ["Hi, Paul!" 43]
By way of contrast, strings in Java and Python are immutable;
you cannot modify a string in either of those languages. In
the case of Python, I believe the decision was made with a
view to performance optimization.
In the case of Java, the decision was made for security
purposes. A common security device is for an argument (string
or buffer) to be validated by a routine that only hands it on
for processing if its contents are acceptable. This could be
defeated by code running in a separate thread if that hostile
code waits long enough for the validation to be performed and
then modifies the content of the argument (string or buffer)
to ask for something else that wouldn't have passed validation.
By making strings immutable, Java protects itself from that
type of security attack.
Hope this helps!
-jn-
------------------------------------------------------------
Programming languages: compact, powerful, simple ...
Pick any two!
joel'dot'neely'at'fedex'dot'com