From: dblack@... Date: 2003-08-17T09:33:03+09:00 Subject: Re: Newbie Q: Data encapsulation with Ruby Hi -- On Sun, 17 Aug 2003, Joe Cheng wrote: > > Ruby is good this way: objects can choose to expose their state > > directly, *but then they can change to having more complex method-based > > access.* [emphasis added] > > Once again, Dave Thomas hits the nail on the head. The reason attr_reader > and attr_writer are OO-approved (at least, to the degree that Java getX and > setX accessors are) is because you can override their behavior later. The > same would not be true of making Java fields public, since there is no way > you can "intercept" direct field access and no way to write methods that > look like direct field access. (I think the same is true in C++?) Ruby also has the #private method (referred to wrongly by me, earlier, as a keyword), so you could do for example: class C attr_reader :a private attr_writer :a def something # you can use #a= here end end C.new.a = 1 # error -- private method called In other words, you can layer access levels on top of the attr_*-generated methods (and others, of course). David -- David Alan Black home: dblack@superlink.net work: blackdav@shu.edu Web: http://pirate.shu.edu/~blackdav