amarquis has asked for the wisdom of the Perl Monks concerning the following question:
This is probably a strange question, and will show how little OO work I've done. But, I've been thinking about it lately so here goes nothin':
I get the idea behind encapsulation, you provide a public interface of methods to get and set data so the user doesn't mess around under the hood.
But, what about in the module itself? Say I've a Perl module that takes in some data, stores it as an internal representation, has some manipulation methods, and finally outputs the data. Should those manipulation methods be aware of the underlaying representation, or should they too use getters and setters?
Specific example: I'm currently working on a module at $work to help with a task simliar to what I mention above (data in, maybe manipulation, data out in new format). The object itself is a blessed hash reference, and the main data gets stored in a 2-d array, a reference to which is in the hash.
Say I've a method that needs to find a cell in that matrix and modify it. Should it use $self->getcell($x, $y) or $self->{'dataref'}[$x][$y]?
On one hand, using the getters/setters provides the benefits of encapsulation inside the class. I'd be able to seamlessly change the data structure with little work. And were there things I wanted to track about each get and set, I could track them right in the getters/setters, knowing everything went through them.
On the other hand, I've got many, MANY operations to do, and adding a few million subroutine calls slows things down significantly (but not insufferably). This is the argument I've always allowed to sway me, and until I began playing around with this idea I always let my modules directly access the underlaying data structures.
This may very well be a dumb question in addition to a strange one, but I'm still curious as to what the prevailing wisdom is on this.
|
---|
Replies are listed 'Best First'. | |
---|---|
Re: Does one encapsulate a class from itself?
by ikegami (Patriarch) on Mar 06, 2008 at 17:34 UTC | |
Re: Does one encapsulate a class from itself?
by herveus (Prior) on Mar 06, 2008 at 17:48 UTC | |
Re: Does one encapsulate a class from itself?
by kyle (Abbot) on Mar 06, 2008 at 18:44 UTC | |
by amarquis (Curate) on Mar 06, 2008 at 20:24 UTC | |
by kyle (Abbot) on Mar 06, 2008 at 23:19 UTC | |
Re: Does one encapsulate a class from itself?
by chromatic (Archbishop) on Mar 06, 2008 at 18:05 UTC | |
by amarquis (Curate) on Mar 06, 2008 at 19:39 UTC | |
Re: Does one encapsulate a class from itself?
by guaguanco (Acolyte) on Mar 07, 2008 at 00:22 UTC | |
Re: Does one encapsulate a class from itself?
by dynamo (Chaplain) on Mar 07, 2008 at 00:20 UTC | |
Re: Does one encapsulate a class from itself?
by toma (Vicar) on Mar 07, 2008 at 08:14 UTC |