M
Mohammad Khan
Mohammad said:But what about scenario 2? [methods changes state of an Object that
it gets as an argument] Scenario 2 is not acting as scenario 1, is it
because scenario 2 gets object rather than variable? Or, Scenario 2
gets clonable object while scenario 1 not?
First, let's agree on using the term "mutable" (or "changeable") instead
of "cloneable". (Immutable objects can not be cloned most of the time,
but the both terms are not strictly the same things.)
agreed on using term 'mutable'.
Scenario 2 changes attributes of an Object. This is something that is
entirely possible. It makes sense for a CarFactory object to be stopped
or running -- it also makes sense that you are able to stop or (re)start
such an object at run time. What can not be done is changing the value
of a variable that appeared in the method invocation because the method
does not know anything about the variable -- it gets the Object. Objects
can have state that can be changed. This can happen via accessors that
are invoked like obj.foo = x or other methods like car_factory.stop.
But while obj.foo looks similar to variable assignment it is something
entirely else.
Why do different things look so similar in Ruby? It's uniform access at
work.
In other languages there usually is the distinction between Object's
fields and methods. Having public fields is usually a bad idea (it
breaks encapsulation) and looks like this:
obj.field += 5
Having methods that modify state looks like this:
obj.setField(obj.getField() + 5)
In Ruby both look like this:
obj.field += 5
Even if obj.field=() or obj.field() do not directly map to an instance
variable at all like in this case:
def obj.radius()
@diameter / 2
end
def obj.radius=(new_radius)
@diameter = new_radius * 2
end
I hope this explains how Ruby works. If there is still anything left
that you don't understand, feel free to ask.
Thanks for your GREAT explanation.
In my two scenarios, we were dealing with two things: variable and object.
If everything is object ... variable is coming from where?
In other words, what is the relation between variable and object.
Are non-mutable objects considered as variables?
Thanks again,
MOhammad