Forum: Ruby Private attribute or accessor?

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Ca0b18ec9e11dc777b2b8084fe5d5f90?d=identicon&s=25 Sam Kong (Guest)
on 2005-12-13 18:15
(Received via mailing list)
Hi!

See the following codes.

[1]
class C
  attr_accessor :a
  def f(v)
    @a = v
    ...
  end
end

[2]
class C
  attr_accessor :a
  def f(v)
    a = v
    ...
  end
end


[1] and [2] work exactly same.
I wonder which way is more proper.

In my opinion, if there're accessors (getter and setter), using them in
the class is better than directly accessing the instance data.
However, most codes I've seen access the data directly.

What do you think?

Sam
47b1910084592eb77a032bc7d8d1a84e?d=identicon&s=25 Joel VanderWerf (Guest)
on 2005-12-13 18:21
(Received via mailing list)
Sam Kong wrote:
> class C
>   attr_accessor :a
>   def f(v)
>     a = v
       ^^^^^ this only assigns a local variable

You want:

       self.a = v
47b1910084592eb77a032bc7d8d1a84e?d=identicon&s=25 Joel VanderWerf (Guest)
on 2005-12-13 18:24
(Received via mailing list)
Sam Kong wrote:
> In my opinion, if there're accessors (getter and setter), using them in
> the class is better than directly accessing the instance data.
> However, most codes I've seen access the data directly.
>
> What do you think?

I tend to agree. It's more flexible if you later need to redefine the
accessors to do some extra computation or store the value differently.
0817571d150afead454f4220007042fe?d=identicon&s=25 Matthew Desmarais (Guest)
on 2005-12-13 18:33
(Received via mailing list)
Sam Kong wrote:

>  end
>
>Sam
>
>
Hi Sam,

Just a quick point: your examples don't work the same way.  In [2],
you'll want to replace a = v with self.a = v.

Regards,
Matthew
Ca0b18ec9e11dc777b2b8084fe5d5f90?d=identicon&s=25 Sam Kong (Guest)
on 2005-12-13 18:54
(Received via mailing list)
Oops!

Right.
a should be self.a.

Sorry!

Sam
669b7046f02e5dfc4bda4421f1069731?d=identicon&s=25 Alex Fenton (Guest)
on 2005-12-13 21:43
(Received via mailing list)
Sam Kong wrote:

> In my opinion, if there're accessors (getter and setter), using them in
> the class is better than directly accessing the instance data.
> However, most codes I've seen access the data directly.

Another advantage of using accessor methods (self.foo = ) over variables
(@foo =) is that it can help avoid typo bugs. Variables are initialised
to nil, so if you write @the_variable in one place and later elsewhere
read @thevariable, you don't get an immediate complaint. If you typo an
accessor method, you get an immediate NoMethodError .

I've moved to this style over time - also because it's easier (I find)
to do things using method reflection - eg adding and notifying
observers.

a
This topic is locked and can not be replied to.