On Mon, 2 Jan 2006 09:37:45 +0900, Jonathan L.
[email protected]
wrote:
Can’t change the value of self (SyntaxError)
self = round_to *args
Why doesn’t it work? What can I do instead?
One way of thinking about reassigning self is if you imagine in a
numeric class
saying
def double
self *= 2
end
That would amount to saying, if we did 1.double,
1 becomes 2
which would mean that 1+1 would thereafter be 4, and that would be bad.
What we need is not the value 1 to become 2, but to get the value 2 back
when we
say 1.double. So we say
def double
return self*2
end
or, since “return” is implied
def double
self*2
end
In general in OO, an object can change its contents, but it cannot
change its
“self”. What should happen in this program?
one = 1
another_one = 1
assert_equal(2, one+one)
assert_equal(2, another_one+another_one)
one.double
assert_equal(4, one+one)
assert_equal(???,another_one+another_one)
assert_equal(???, 1+1)
When we double one, if the self*=2 thing worked, the ??? asserts would
also find
4. We might be able to understand another_one being 2, but to have all
occurrences of 1+1 in the program turn into 4 … that would be bad.
Certain objects are called “value objects”, and the idea is that like
numbers,
they never change value. For many objects it is a design choice whether
or not
to make them value objects, even if they are quite complex. For example,
in the
articles I’m currently writing on extended set theory on my site, I’m
moving in
the direction of making my sets value objects. They are essentially
arbitrarily
large collections of records (like relational database relations), and
most DB
apps think of relations as mutable. I’m going to make a different
decision,
namely that any set, once created, is a constant. It’ll be interesting
to see
what happens.