Sunday, 15 March 2009

Accessors

In Ruby, variables are always private; they cannot be directly accessed from outside the object (constants are always public). However, it is often the case that you do need to allow some access. One way would be to define methods that set and get the values. For example:
class TestClass
def initialize id, name
@id = id
@name = name
end

def id
@id
end

def name
@name
end

def name= s
@name = s
end
end

# Test it works properly
tc = TestClass.new 12, 'Boris'
p tc.id
p tc.name
tc.name = 'Alfie'
p tc.name

Note that the id cannot be set after the object is created; it is a read-only attribute.

Ruby offers a short cut for getters and setters. The above class can be re-written like this:
class TestClass
def initialize id, name
@id = id
@name = name
end

attr_reader :id
attr_accessor :name
end

The class behaves just the same, so the test code will work here as well, but all that clutter has been removed.

There is also a method for write-only attributes, and several attributes can be listed, separated with commas:
attr_reader :size, :address, :dir

What is happening is that attr_reader is a method (in the Module class), that takes the parameter :id, and dynamically defines the id method.

Having said that, here is an interesting article (written for Java, but applicable to any object-orientated language) about why getters and setters are evil (sometimes):
http://www.javaworld.com/javaworld/jw-09-2003/jw-0905-toolbox.html

Struggling with Ruby: Contents Page

No comments: