"Meino Christian Cramer" <mccramer / s.netic.de> wrote in message
news:20030816.173048.74736153.mccramer / s.netic.de...
> Hi,
>
>  as a beginner in C++ I learned that one advantage of OOP over the
>  procedural programming is data hiding and encapsulation.

well yes - some advanced programmers would claim that encapsulation is
overrated - enter functional programming. Anyway it has its advantages as
long as you don't turn it into a source code management nightmare.

>
>  In C++ this is achieved via the public:, protected: and private:
>  keywords.

ruby has the private keyword, but you can override it if you really want to
(and you can cast pointers in C++).

>  As I currently (try to) understand, Ruby does it somehow different.
>
>  class A
>    def initializer( k_a )
>      @a = k_a
>    end
>  end
>
>  will declare a class A with a "totally private" attribute "a", which
>  only can be accessed vie get/set-combos.
>
>  Now I found (for me astonishling) two keywords:
>
> attr_reader:
>
>  and
>
> attr_writer:

These are auto-implementations of getter and setter methods - no more, no
less.
Nobody forces you to write them - and at any time you can remove them an
replace them with custom getter setter methods without affecting client
code.

Please refer to the Programming Ruby book by Thomas & Hunt - its available
online
http://www.rubycentral.com/book/


>  which (seems to) totally "inifiltrate" the principle of data hiding
>  and encapsulation.

Not at all - on the contrary Ruby never provides direct access to member
data.
What ruby does allow is for an external user to add new methods to class and
thus indirectly provide access to class. Thus data-hiding is a matter of
policy not enforcement.

The real benefit of getter setter methods is not data hiding but
abstraction:

Consider a collection class. At one point in its development cycle it has a
@count property and a linked list for data storage. Later it uses the Array
class for storage and relies on the array to do the counting.
If external users had direct access to the @count member, it would be
difficult to change. But now you can just write a new getter method for
count when replacing the array.

To take this example to functional programming: you would have a record
field storing the count value and a function get_count to extract the count
value. When the implementation changes you break the get_count function and
any other direct access to the count field. But since the code hopefully is
developed in a clean modular fashion, it is sufficient to update the
get_count method. Used in a discplined way this leads to faster development.
Actually there is a kind of data-hiding because you typically have a module
with public functions and hidden data structures.

Mikkel