The reason is pretty straightforward. Say later on you want to alter the
behaviour of your getter or setter, you only need do this in 1 place,
rather than hunting down every mention of the instance variable.
Person = Struct.new :age, :gender, :sex do
def describe
"A #{age} year old {gender} who lives in #{location}"
end
end
In other words: Struct does not define instance variables - you can
only access them via accessor methods.
Kind regards
robert
···
On Mon, Jan 6, 2014 at 11:27 PM, Joel Pearson <lists@ruby-forum.com> wrote:
The "best practice" way of doing this is:
self.age = age
self.gender = gender
self.location = location
The reason is pretty straightforward. Say later on you want to alter the
behaviour of your getter or setter, you only need do this in 1 place,
rather than hunting down every mention of the instance variable.
The reason is pretty straightforward. Say later on you want to alter the
behaviour of your getter or setter, you only need do this in 1 place,
rather than hunting down every mention of the instance variable.
When I need the setter only for the constructor method then defining a
setter for the instance automatically seems to be in violation of YAGNI;
beside this if I want to keep the API of the instance/object strict, I
would have to make those setters private.
My 'best' practice is to use the @variable assignment within the
constructor when I don't want the object to change it during its
life-cycle and to use the setter when I expect the @variable to change
outside of constructor.