[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

Private attribute or accessor?

Sam Kong

12/13/2005 5:08:00 PM

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

5 Answers

Joel VanderWerf

12/13/2005 5:19:00 PM

0

Sam Kong wrote:
> class C
> attr_accessor :a
> def f(v)
> a = v
^^^^^ this only assigns a local variable

You want:

self.a = v

--
vjoel : Joel VanderWerf : path berkeley edu : 510 665 3407


Joel VanderWerf

12/13/2005 5:21:00 PM

0

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.

--
vjoel : Joel VanderWerf : path berkeley edu : 510 665 3407


Matthew Desmarais

12/13/2005 5:32:00 PM

0

Sam Kong wrote:

>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
>
>
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


Sam Kong

12/13/2005 5:49:00 PM

0

Oops!

Right.
a should be self.a.

Sorry!

Sam

Alex Fenton

12/13/2005 8:41:00 PM

0

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