views:

316

answers:

3

I saw a code

class Person
  def initialize(age)
    @age = age
  end

  def age
    @age
  end

  def age_difference_with(other_person)
    (self.age - other_person.age).abs
  end

protected :age
end

What I want to know is how difference between using @age and self.age in age_difference_with method.

+2  A: 

The difference is that it is isolating the use of the method from the implementation of it. If the implementation of the property were to change -- say to keep the birthdate and then calculate age based on the difference in time between now and the birthdate -- then the code depending on the method doesn't need to change. If it used the property directly, then the change would need to propagate to other areas of the code. In this sense, using the property directly is more fragile than using the class-provided interface to it.

tvanfosson
A: 

There isn't any difference. I suspect that it was done just for the documentary value of seeing self.age and other_person.age near each other.

I suppose that use does allow for an actual getter to be written in the future, which might do something more complex than just return an instance variable, and in that case the method would not need to change.

But that's an unlikely abstraction to worry about, after all, if the implementation of the object changed it's reasonable to change other methods, at some point a simple reference within the object itself is perfectly reasonable.

In any case, abstraction of the age property still doesn't explain the explicit use of self, as just plain age would also have invoked the accessor.

DigitalRoss
+7  A: 

Writing @age directly accesses the instance variable @age. Writing self.age tells the object to send itself the message age, which will usually return the instance variable @age — but could do any number of other things depending on how the age method is implemented in a given subclass. For example, you might have a MiddleAgedSocialite class that always reports its age 10 years younger than it actually is. Or more practically, a PersistentPerson class might lazily read that data from a persistent store, cache all its persistent data in a hash.

Chuck
I have once read a book in rails and don't understand the difference between this self and @, so I should always use self.var_name in my methods (that doesn't setter and getter) to make my data using public interface, I spent time defining it in getter and setter, right ?
art