Hello, beloved Perl monks. My learning journey has taken me to a far and exciting land called Object-Oriented Programming (OOP). I find OOP interesting as it entails a different way of thinking and approach in programming. I am currently studying a book, Perl Objects, References & Modules (1993) by Randal L. Schwartz, and was introduced to the concepts of getters and setters. Personally, I do not feel comfortable with the idea of using setter and getter functions. I understood clearly the disadvantages of accessing class objects directly. If down the road I would need to design a class object, I would try to stay away, as possible, from using accessors. However, I am a bit frustrated because the book only illustrated how setters/getters could break the encapsulation of a class object. I made up my own example to illustrate how encapsulation could be broken into despite the success of changing the color attribute from 'red' to ‘green’.
use strict;
use warnings;
{
package Fruit;
sub new {
my $class = shift;
my $fruit = shift;
my $self = { name => $fruit, color => 'red' };
bless $self, $class;
};
sub set_color {
my $self = shift;
$self->{'color'} = shift;
};
sub get_color {
my $self = shift;
$self->{'color'};
};
}
my $obj = Fruit->new('apple');
$obj->set_color('green');
$obj->get_color;
use Data::Dumper;
print Dumper($obj);
I used Data::Dumper and the result is shown below:
$VAR1 = bless( {
+
+
'color' => 'green',
+
+
'name' => 'apple'
+
+
}, 'Fruit' );
The chapter I read, chapter 9, did not offer definitive and non-invasive solutions on updating an object’s attribute. On the other hand, It’s also possible that I have failed to understand some key points in the chapter. My question is, are setters and getters still used these days in Perl programming? Is there a non-invasive way to update an object’s attribute? Is OOP considered a universal subject that it could be discussed without any reference to a particular programming language? Are there books that you could recommend on the subject? Thank you. :)
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.